我目前正在编写Java TCP服务器来处理与客户端的通信(我没有编写)。当托管在Windows上的服务器以接收到的记录数响应客户端时,客户端无法正确读取整数,而是将其读取为空数据包。当Mac上托管的相同服务器代码以收到的记录数响应客户端时,客户端读取数据包并正确响应。通过我的研究,我没有找到似乎可以解决问题的解释。在调用writeInt方法之前,我曾尝试过反转字节(Integer.reverseBytes),但这似乎无法解决问题。任何想法表示赞赏。
布赖恩
比较pcap文件后,它们的发送方式没有明显差异。先发送第一个字节,然后发送最后3个字节。两个系统都发送正确数量的记录。
是的,我指的是DataOutputStream.writeInt()方法。 //添加代码
public void run() {
try {
InputStream in = socket.getInputStream();
DataOutputStream datOut = new DataOutputStream(socket.getOutputStream());
datOut.writeByte(1); //sends correctly and read correctly by client
datOut.flush();
//below is used to read bytes to determine length of message
int bytesRead=0;
int bytesToRead=25;
byte[] input = new byte[bytesToRead];
while (bytesRead < bytesToRead) {
int result = in.read(input, bytesRead, bytesToRead - bytesRead);
if (result == -1) break;
bytesRead += result;
}
try {
inputLine = getHexString(input);
String hexLength = inputLine.substring(46, 50);
System.out.println("hexLength: " + hexLength);
System.out.println(inputLine);
//used to read entire sent message
bytesRead = 0;
bytesToRead = Integer.parseInt(hexLength, 16);
System.out.println("bytes to read " + bytesToRead);
byte[] dataInput = new byte[bytesToRead];
while (bytesRead < bytesToRead) {
int result = in.read(dataInput, bytesRead, bytesToRead - bytesRead);
if (result == -1) break;
bytesRead += result;
}
String data = getHexString(dataInput);
System.out.println(data);
//Sends received data to class to process
ProcessTel dataValues= new ProcessTel(data);
String[] dataArray = new String[10];
dataArray = dataValues.dataArray();
//assigns returned number of records to be written to client
int towrite = Integer.parseInt(dataArray[0].trim());
//Same write method on Windows & Mac...works on Mac but not Windows
datOut.writeInt(towrite);
System.out.println("Returned number of records: " + Integer.parseInt(dataArray[0].trim()) );
datOut.flush();
} catch (Exception ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
datOut.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
如其Javadoc中所述,DataOutputStream.writeInt()根据TCP / IP RFC使用网络字节顺序。这是您所指的方法吗?