Whats the difference between a socket which is open and a socket which is connected?

≯℡__Kan透↙ 提交于 2019-11-28 03:02:32

问题


The Java Socket class has two methods isClosed and isConnected to check whether the socket is closed or connected respectively. I wanted to know what's the difference between a TCP socket which is only open and a TCP socket which is open and connected, and how is this different from UDP.


回答1:


To put things simply, a Socket that is open is a socket that is either waiting for connection or has successfully connected with another Socket. When a socket has been closed, it means that this socket is no longer available for connection, and that it's resources has already been released. A Socket that is connected, well, it means that the socket is connected to another Socket.

So a Socket can..

  • be open and connected at the same time.
  • be open and not connected at the same time.
  • not be connected when closed.

UPDATE

from @Bryan

Apparently, there are half-closed or half-open states for TCP Sockets; which usage (today) is different from its original meaning. More on this link.




回答2:


This page gives a fairly good overview on socket states: http://diranieh.com/SOCKETS/SocketStates.htm and the difference between TCP and UDP sockets. Particularly:

  • State "Open" (TCP and UDP): An unnamed socket has been created. An unnamed socket is one that is not bound to a local address and port
  • State "Connected" (TCP only): An association (virtual circuit) has been established between a local and remote host. Sending and receiving data is now possible.

Note that newer implementations of java.net.DatagramSocket support an extension to the TCP/IP network states: A DatagramSocket can also be in the state "connected", so that isConnected() does not necessarily return false even though a datagram socket is never "connected" at the network layer. In particular: "When a DatagramSocket is connected to a remote address, packets may only be sent to or received from that address. By default a datagram socket is not connected."

For more information, see the sources and the JavaDoc.



来源:https://stackoverflow.com/questions/12685056/whats-the-difference-between-a-socket-which-is-open-and-a-socket-which-is-connec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!