我看到一些关于此的帖子,但我仍然无法找到答案。在Java套接字中关闭流的正确方法
这是我的服务器如何与客户端的交互:
public void run() {
try {
//Read client request
InputStream is = server.getInputStream();
byte[] buff = new byte[1024];
int i;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((i = is.read(buff, 0, buff.length)) != -1) {
bos.write(buff, 0, i);
System.out.println(i + " bytes readed ("+bos.size()+")");
}
is.close();
is = null;
//Do something with client request
//write response
OutputStream os = server.getOutputStream();
os.write("server response".getBytes());
os.flush();
os.close();
os = null;
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
这是客户端:
public void run() {
try {
InetAddress serverAddr = null;
serverAddr = InetAddress.getByName("10.0.2.2");
socket = new Socket(serverAddr, 5000);
//Send Request to the server
OutputStream os = socket.getOutputStream();
os.write(jsonRequest.toString().getBytes("UTF-8"));
os.flush();
os.close();
os = null;
//Read Server Response
InputStream is = socket.getInputStream();
byte[] buff = new byte[1024];
int i;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((i = is.read(buff, 0, buff.length)) != -1) {
bos.write(buff, 0, i);
System.out.println(i + " bytes readed ("+bos.size()+")");
}
is.close();
is = null;
//Do something with server response
} catch (UnknownHostException uhe) {
sendCallbackError(uhe);
} catch (IOException ioe) {
sendCallbackError(ioe);
}
}
正如你可以看到,客户端连接,并发送请求。服务器读取该请求,然后写入客户端将读取的响应。
此代码的问题是客户端中的OutputStream.close()
和服务器中的InputStream.close()
。正如Javadocs所述,关闭该流将关闭Socket
。结果是,当客户端尝试读取服务器响应时,Socket
已关闭。
我已经设法通过调用Socket.shutdownInput
和Socket.shutdownOutput
来解决这个问题。但我仍在考虑这是否是这样做的正确方法
作为一个说明,关闭与close()
当服务器写入响应或当客户端读取它时不会产生问题(我猜想关闭是在客户端和服务器之间同步)。
所以我的问题是:
- 正在使用套接字关闭方法正确的方法是什么?
- 我可以保留(发送和阅读从服务器 响应时)
- 难道发生与关机关闭会保留一些数据 缓冲区,并且不会被发送与
close()
关闭最后一个流?
把socket.close()放在finally块中。 –
@PeterLawrey你的意思是不关闭流并关闭套接字?如果是,我想我应该关闭两端的插座,对吧? – momo
您应该关闭套接字,如果您想先刷新输出流,则可能需要先关闭或刷新它。 –