关闭套接字的输入流是否也会关闭套接字连接? [英] Does closing the inputstream of a socket also close the socket connection?

查看:39
本文介绍了关闭套接字的输入流是否也会关闭套接字连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆