gpt4 book ai didi

java - 在 Java 套接字中关闭流的正确方法

转载 作者:行者123 更新时间:2023-12-01 14:20:45 25 4
gpt4 key购买 nike

我看到了一些关于此问题的帖子,但我仍然找不到答案。

这就是我的服务器与客户端交互的方式:

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() 关闭流不会产生问题(我猜关闭在客户端和服务器之间是同步的) .

所以我的问题是:

  1. 使用 Socket 关闭方法是否正确?
  2. 我可以使用 close() 继续关闭最后一个流吗(发送和读取时)来自服务器的响应)
  3. 通过 shutdown 关闭是否会保留一些数据缓冲区并且不会被发送?

最佳答案

您可以执行以下操作:

try{
}catch(){
}finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}

关于java - 在 Java 套接字中关闭流的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com