我有一个TCP服务器-客户端对。客户端有一个线程用于处理来自服务器的数据。问题是,在从服务器接收到第一个数据之前,Buffered读取器被阻塞。但一旦接收到第一个数据,它就会在无用数据之间不断发送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(字符串argv[])引发异常{ServerSocket welcomeSocket=新的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;
}
}
您正在写32位的int,在您的情况下,所有的int都有三个前导零字节,而正在读取16位的chars,因此您读取的每个奇数chars都由两个零字节组成。这没有任何意义。如果你用writeInt()
写作,就用readInt()
阅读。所有其他DataInput/OutputStream
方法也是如此。对称使用。
这里没有任何证据表明有任何东西没有阻塞。