我有一个 TCP 服务器客户端对。客户端有一个线程用于处理来自服务器的数据。问题是,在从服务器接收到第一个数据之前,缓冲读取器被阻塞。但是一旦收到第一个数据,它就会在有用的数据之间不断发送 0。有谁知道为什么?以及如何解决这个问题?
connection = new Socket(ip, port);
output = new DataOutputStream(connection.getOutputStream());
input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
并且这部分被修改以处理 0,但这并不理想:
try {
opcode = (char) input.read();
} catch (IOException ex) {
ErrorFrame erfframe = new ErrorFrame("De verbinding is verbroken voordat we de opcode van het packet konden lezen", "Herverbinden", IRIGui.ConnectionType);
}
System.out.println("Data received!!" + opcode);
int opcodenr = Character.getNumericValue(opcode);
char sensortype = '0';
try {
do {
sensortype = (char) input.read();
} while (sensortype == 0);
} catch (IOException ex) {
ErrorFrame erfframe = new ErrorFrame("De verbinding is verbroken voordat we de sensortype van het packet konden lezen", "Herverbinden", IRIGui.ConnectionType);
}
服务器代码:
public static void main(String argv[]) throws Exception { ServerSocket welcomeSocket = new ServerSocket(25566);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
int request = inFromClient.read();
System.out.println("erjioejfioe " + request);
if (request == 4) {
outToClient.writeBytes("41");
outToClient.write(5);
outToClient.writeInt(5);
outToClient.writeInt(3);
outToClient.writeInt(6);
outToClient.writeInt(5);
outToClient.writeInt(1);
}
request = 0;
request = inFromClient.read();
System.out.println("erjioejfioe " + request);
if (request == 4) {
System.out.println("SENDING THE SHIT");
outToClient.writeBytes("41");
outToClient.write(5);
outToClient.writeInt(3);
outToClient.writeInt(7);
outToClient.writeInt(2);
outToClient.writeInt(4);
outToClient.writeInt(3);
System.out.println("We get here!!");
}
break;
}
}