您的实施存在问题
BufferedReader#readLine http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
:
读取一行文本。一行被视为由换行符 ('\n')、回车符 ('\r') 或回车符后紧跟换行符之一终止。
换句话说,如果您的客户从未发送过\n
or \r
字符该方法将不会结束,直到IOException
由于断开连接而被抛出。
Solution
替换这段代码:
BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String clientData = "";
clientData = reader.readLine();
with:
int red = -1;
byte[] buffer = new byte[5*1024]; // a read buffer of 5KiB
byte[] redData;
StringBuilder clientData = new StringBuilder();
String redDataText;
while ((red = clientSocket.getInputStream().read(buffer)) > -1) {
redData = new byte[red];
System.arraycopy(buffer, 0, redData, 0, red);
redDataText = new String(redData,"UTF-8"); // assumption that client sends data UTF-8 encoded
System.out.println("message part recieved:" + redDataText);
clientData.append(redDataText);
}
System.out.println("Data From Client :" + clientData.toString());
InputStream#read http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read(byte%5B%5D)
:
从输入流中读取一定数量的字节并将它们存储到缓冲区数组 b 中。实际读取的字节数以整数形式返回。此方法会阻塞,直到输入数据可用、检测到文件结尾或引发异常。
将在执行时读取尽可能多的字节 - 它基本上是缓冲读取。由于这些是原始字节,当将它们转换为字符串 http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String(byte%5B%5D,%20java.nio.charset.Charset)您必须知道其编码才能正确显示它们(即“UTF-8”部分)。如果encoding http://en.wikipedia.org/wiki/Character_encoding其中您的客户端发送字节是其他的,您可能需要更改它才能在控制台输出中获得正确的文本。
我建议阅读官方教程:
- 字节流 http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html
- 字符流 http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
- 缓冲流 http://docs.oracle.com/javase/tutorial/essential/io/buffers.html