我有一个 Java 中的 TCP 客户端
,它与 C# TCP 服务器
进行通信,反之亦然。它们通过发送字节数组进行通信。我在读取客户端中的字节数组时遇到问题。字节数组的固定长度为 4。
例如,当服务器发送:
[2, 4, 0, 2]
[2, 4, 0, 0]
客户端输出是:
Connecting to port :10000
Just connected to /192.168.1.101:10000
Server says [2, 4, 0, 0]
我该如何解决这个问题?看起来第一个数组被覆盖了?
TCPClient.java
public class TCPClient {
private OutputStream outToServer=null;
private DataOutputStream out=null;
private ByteProtocol byteProtocol;
Socket client;
InputStream inFromServer;
DataInputStream in;
public void initConnection(){
try {
int serverPort = 10000;
InetAddress host = InetAddress.getByName("192.168.1.101");
System.out.println("Connecting to port :" + serverPort);
client = new Socket(host, serverPort);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
outToServer = client.getOutputStream();
out=new DataOutputStream(outToServer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void readBytes(){
try {
inFromServer = client.getInputStream();
in = new DataInputStream(inFromServer);
byte[] buffer = new byte[4];
int read = 0;
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
in.read(buffer);
System.out.println("Server says " + Arrays.toString(buffer));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void sendBytes(byte [] byteArray) throws IOException{
out.write(byteArray);
}
public void closeClient() throws IOException{
client.close();
}
}
最佳答案
看起来您正在读取缓冲区两次:
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
in.read(buffer);
因此循环头中读取的内容会被第二个read()
覆盖。
关于java - 从 DataInputStream 读取字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728722/