以下是我的客户端/服务器流程:
在主线程中创建Socket。
- 将Socket传递给线程1。
- 客户端向服务器发送数据。
- 服务器响应客户端。
- 服务器通过调用
close()
关闭输入流、输出流和套接字。 - Socket返回到主线程,然后传递给线程2。
- 客户端向服务器写入数据-没有异常、没有错误,服务器没有收到任何数据。
- 客户端尝试读取数据-没有异常、没有错误。
如何检测套接字已关闭的问题?
try {
os = new DataOutputStream(this.socket.getOutputStream());
os.write(data);
os.flush();
System.out.println("Written " + data.length + " bytes");
} catch (IOException e) {
System.out.println("Client failed to write to stream");
System.out.println(e.getMessage());
e.printStackTrace();
}
异常从未被抛出。它显示“已写入60个字节”。有什么想法吗?
更新
这是我读取响应的方式。等待数据,读取前4个字节(这给出响应的长度),并继续读取,直到读取指定长度。由于没有数据进来,此循环永远不会结束。
is = new DataInputStream(this.socket.getInputStream());
while(true){
while(is.available() > 0){
bos.write(is.read());
}
if(contentLength == 0 && bos.size() > 3){
byte[] bytes = bos.toByteArray();
byte[] size = Arrays.copyOf(bytes, 4);
contentLength = ByteBuffer.wrap(size).getInt();
}
if(bos.size() - 4 < contentLength){
continue;
}
break;
}
available()
必须返回零。 - erickson