【发布时间】:2017-05-30 14:34:50
【问题描述】:
我需要将两个 TCP 数据包合并为一个。我编写了一个套接字仿真器,它从 csv 文件中读取一行数据,并每秒将每一行数据输出到两个 99 字节的二进制数据包中。我现在需要编写另一个模拟器,将这两个 99 字节数据包合并为一个 198 字节数据包。
这就是我到目前为止所汇总的内容,它基本上从一个模拟器转发两个 99 字节数据包,并将其作为两个 99 字节数据包中继到客户端。我尝试了几种不同的方法,但似乎无法弄清楚如何将两者合并为一个 198 字节的数据包。听起来很简单,但我无法理解它,建议将不胜感激。谢谢
package PacketFuser;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class PacketFuser {
public static void main(String args[]) throws IOException{
//Start server
Socket socket = null;
final ServerSocket ss = new ServerSocket(6666);
System.out.println("Waiting on connection...");
while (ss.isBound()){
try {
socket = ss.accept();
System.out.println("Connected to port: " +socket.toString());
}
catch (IOException e){
}
//Start Client Socket
InetAddress address=InetAddress.getLocalHost();
Socket c1=null;
boolean client = false;
while (client == false){
try{
System.out.println("waiting on Emulator");
Thread.sleep(1000);
c1=new Socket(address, 31982);
client = true;
}
catch (IOException e){}
catch (InterruptedException ex) {}
}
System.out.println("Emulator Connected");
//I need to figure out here how to catch two packets and merge them into one 198 byte packets here.
DataInputStream in = new DataInputStream(s1.getInputStream());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int pread;
byte[] p1 = new byte[99];
while ((pread = in.read(p1, 0, p1.length)) != -1 ) {
buffer.write(p1, 0, pread);
buffer.flush();
socket.getOutputStream().write(p1);
}
}
}
}
【问题讨论】:
-
你的所作所为毫无意义。 TCP 是基于流的——在应用程序级别上没有 99 字节或 198 字节的数据包。您可以通过 40 和 59 字节的读取来获得前 99 字节。即使您尝试一次写入 198 字节,另一方也可能会以完全不同的块读取它们。
-
如果有办法做到这一点,我看不出它是多么毫无意义..