早上好,我对python中的字节对象(表示为b'')与如何在Java中复制字节对象之间的区别有一个简短的疑问。
我正在从事的项目是在死服务器的仿真服务器上进行一些个人工作,以提高我的倒车技能。我在python中有该项目的有效版本,但由于我对语言更好,因此想切换到Java,它附带了许多其他工具,这些工具对于像这样的项目很有用。
我正在使用ServerSocket捕获Java项目中的TCP数据。
当数据从Python项目通过网络传入时,看起来有点像这样:
当我通过java ServerSocket捕获相同的数据时,会得到如下信息:
我的问题是我如何重新格式化该ASCII文本以获取正确的数据,如该软件的python版本所示。
目前,我能够获得如下输出:
while(true) {
try {
Socket socket = serverSocket.accept();
onConnection(socket);
byte[] incomingData = new byte[0];
byte[] temp = new byte[1024];
int k = -1;
//this is due to the client of said game not sending EOL (readLine() does not work here)
while((k = socket.getInputStream().read(temp, 0, temp.length)) > -1) {
byte[] tbuff = new byte[incomingData.length + k];
System.arraycopy(incomingData, 0, tbuff, 0, incomingData.length);
System.arraycopy(temp, 0, tbuff, incomingData.length, k);
incomingData = tbuff;
receiveData(socket, incomingData); <--- this is the important bit
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void receiveData(Socket socket, byte[] data) {
int lenLo = (int) (data[0]);
int lenHi = (int) (data[1]);
int length = lenHi * 256 + lenLo;
if(lenHi < 0) {
System.out.println("Invalid Packet Length");
}
if(data.length != length) {
System.out.println("Incomplete Packet Received");
}
try {
String test = new String(data, "UTF-8");
serverGUI.serverDebug(test); //produces the string in a jframe (pic 2)
serverGUI.debugByteArray(test.getBytes(StandardCharsets.UTF_8)); //produces the byte[] in jframe (pic 3 -- all bytes in this array are & 0xff prior to being printed out)
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
但是,这显然没有产生预期的结果。感谢任何建议或感谢可以提出的任何资源。
谢谢!