我需要將兩個TCP數據包合併爲一個。我編寫了一個套接字模擬器,它從csv文件中讀取一行數據,並將每行數據每秒輸出爲兩個99字節的二進制數據包。我現在需要編寫另一個模擬器,將這兩個99字節的數據包合併成一個198字節的數據包。將兩個99字節的TCP數據包合併爲一個198字節的TCP數據包。
這是我到目前爲止所做的工作,它基本上從一個仿真器轉發兩個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字節的數據包。您已經可以讀取第一個99字節,並讀取40和59字節。即使你試圖一次寫入198byte,另一方也可能讀取完全不同的數據塊。 – Matthias247
我看不出它是多麼毫無意義,如果有辦法做到這一點.. – J4VA