给你我以前两个函数,是阻塞性函数,我现在是使用一个读进程类、一个写进程类进行Socket操作,
这两个函数不支持中文,因为是 utf-8 编码,你可以直接使用 byte[] 进行 utf-16be 编码进行中
文支持
/** Writing Text to a Socket */
public final static void writeSocket(Socket sk, StringBuffer sb)
{
sb.append(sFinished);
writeSocket(sk, sb.toString());
}
/** Writing Text to a Socket */
public synchronized final static void writeSocket(Socket socket, String str)
{
try
{
OutputStream os = socket.getOutputStream();
DataOutputStream ostream = new DataOutputStream(os);
ostream.writeUTF(str);
ostream.flush();
}
catch (IOException e)
{
throw new RuntimeException("Write Socket Exception.");
}
}
/** Reading Text from a Socket */
public synchronized final static String readSocket(Socket socket)
{
try
{
InputStream is = socket.getInputStream();
DataInputStream istream = new DataInputStream(is);
return istream.readUTF();
}
catch (IOException e)
{}
return null;
}
/** Reading Text from a Socket */
/*
public synchronized final static String readSocket(Socket socket)
{
int bufferSize = 40960;
int resultSize = 0;
int readSize = 0;
char c[] = new char[bufferSize];
try
{
InputStreamReader in = new InputStreamReader(socket.getInputStream());
while (true)
{
readSize = in.read(c, resultSize, bufferSize - resultSize);
if (readSize < 0)
break;
resultSize += readSize;
}
}
catch (Exception e)
{}
return new String(c, 0, resultSize);
}
*/