【发布时间】:2015-06-26 01:08:10
【问题描述】:
我在 Java 中有一个 TCP Client,它与 C# TCP Server 通信,反之亦然。他们通过发送byte 数组进行通信。我在读取客户端中的字节数组时遇到问题。字节数组的固定长度为 4。
例如当服务器发送时:
[2, 4, 0, 2]
[2, 4, 0, 0]
客户端输出为:
连接到端口:10000
刚刚连接到/192.168.1.101:10000
服务器说 [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();
}
}
【问题讨论】: