我看到一些關於此的帖子,但我仍然無法找到答案。在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
您應該關閉套接字,如果您想先刷新輸出流,則可能需要先關閉或刷新它。 –