您遇到的问题与TCP流媒体性质有关。
您从服务器发送100个字节的事实并不意味着您第一次阅读时会在客户端中阅读100个字节。也许从服务器发送的字节以几个TCP段到达客户端。
您需要实现一个循环,直到收到整个消息。让我提供一个例子 DataInputStream
代替 BufferedinputStream
. 。简单地为您提供一个例子。
假设您事先知道服务器是发送100个字节的数据。
在客户中,您需要写:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
while(!end)
{
int bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == 100)
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
现在,通常不知道一个节点(此处的服务器)发送的数据大小。然后,您需要为服务器和客户端(或任何两个节点)与TCP通信之间的通信定义自己的小协议。
最常见和简单的是定义TLV:类型,长度,值。因此,您定义了将每个消息发送到客户端的每条消息发送给客户端的信息:
- 1个字节指示类型(例如,也可能是2个字节)。
- 1个字节(或其他)以获取消息长度
- 值的n字节(n表示为n)。
因此,您知道您必须至少收到2个字节,并且使用第二个字节,您知道需要阅读多少个字节。
这只是可能的协议的建议。您也可以摆脱“类型”。
因此,它会像:
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
int bytesToRead = messageByte[1];
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length == bytesToRead )
{
end = true;
}
}
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
以下代码编译并看起来更好。它假设前两个字节提供长度以二进制格式到达网络端(Big Endian)。对于其他消息,不关注不同的编码类型。
import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
class Test
{
public static void main(String[] args)
{
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try
{
Socket clientSocket;
ServerSocket server;
server = new ServerSocket(30501, 100);
clientSocket = server.accept();
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
int bytesRead = 0;
messageByte[0] = in.readByte();
messageByte[1] = in.readByte();
ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);
int bytesToRead = byteBuffer.getShort();
System.out.println("About to read " + bytesToRead + " octets");
//The following code shows in detail how to read from a TCP socket
while(!end)
{
bytesRead = in.read(messageByte);
dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() == bytesToRead )
{
end = true;
}
}
//All the code in the loop can be replaced by these two lines
//in.readFully(messageByte, 0, bytesToRead);
//dataString = new String(messageByte, 0, bytesToRead);
System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}