在我的 Java 应用程序中,打开了一个 Socket,并且正在从其 InputStream 中读取数据。
在最佳条件下,每个传入的数据包都会调用 read() 返回其应用层数据。这就是我想要得到的 - 每个数据包一个“消息” 。
但是,数据可能会根据 getReceiveBufferSize() 返回的内容在套接字中缓冲。如果发生这种情况并从中读取流,则可能存在来自多个数据包的数据。
是否有另一种方法可以从单个数据包中获取数据,或者这是否违反了抽象层?或者,是否可以为数据附加到缓冲区设置某种分隔符?还是平台级别的事情无法完成?
这是一些示例代码来演示我在做什么:
import java.io.InputStream;
import java.net.Socket;
public class Belnets {
public Belnets() {
try{
Socket s = new Socket("address", 23);
System.out.println("platform will buffer this much: "+s.getReceiveBufferSize());
InputStream sin = s.getInputStream();
byte[] data = new byte[1024];
int c;
while(true){
c = sin.read(data);
for(int i=0; i<c; i++){
System.out.print((char)data[i]);
}
System.out.println("=END OF READ=");
//if you dont do this, read() seems to return once for each packet as this loop
//appears to be running fast enough to keep up with the rate of data that comes in.
//otherwise data gets buffered and you get multiple packets worth of data before seeing
//=END OF READ=
Thread.sleep(1000);
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
new Belnets();
}
}