关闭套接字的输入流是否也会关闭套接字连接?

编程入门 行业动态 更新时间:2024-10-23 16:15:02
本文介绍了关闭套接字的输入流是否也会关闭套接字连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在 Java API 中,

<前><代码>套接字套接字 = serverSocket.accept();BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintWriter toSocket = new PrintWriter(socket.getOutputStream());//用fromSocket做某事...并关闭它fromSocket.close();//然后再次写入套接字toSocket.print("socket 连接是否仍然可用?\r\n");//关闭套接字socket.close();

在上面的代码中,当我从Socket关闭InputStream之后,socket连接似乎不再可用——客户端不会收到socket连接仍然可用"的消息.这是否意味着关闭套接字的输入流也会关闭套接字本身?

解决方案

是的,关闭输入流会关闭套接字.您需要在套接字上使用shutdownInput 方法,以仅关闭输入流:

//用fromSocket做某事...并关闭它socket.shutdownInput();

然后,你仍然可以发送到输出套接字

//然后再次写入sockettoSocket.print("socket 连接是否仍然可用?\r\n");//关闭套接字socket.close();

In Java API,


Socket socket = serverSocket.accept();
BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter toSocket = new PrintWriter(socket.getOutputStream());
//do sth with fromSocket ... and close it
fromSocket.close();
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();

In the above code, after I close the InputStream fromSocket, it seems that the socket connection is not available anymore--the client wont receive the "is socket connection still available" message. Does that mean that closing the inputstream of a socket also closes the socket itself?

解决方案

Yes, closing the input stream closes the socket. You need to use the shutdownInput method on socket, to close just the input stream:

//do sth with fromSocket ... and close it 
socket.shutdownInput(); 

Then, you can still send to the output socket

//then write to socket again 
toSocket.print("is socket connection still available?\r\n"); 
//close socket 
socket.close(); 

这篇关于关闭套接字的输入流是否也会关闭套接字连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 16:16:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/942733.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:也会

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!