Socket.Close doesn't really close tcp socket? (c#)

前端 未结 4 707
时光取名叫无心
时光取名叫无心 2021-02-05 22:16

It seems that using socket.Close() for a tcp socket, doesn\'t fully close the socket. In the following example I\'m trying to connect to example.com at port 9999, which is not o

相关标签:
4条回答
  • 2021-02-05 22:56

    You are initialising a new Socket in every Loop... with *.close() you close the old and at the begin you are creating a new one with the same parameters as the Socket before.

    0 讨论(0)
  • 2021-02-05 22:59

    It will close the .NET part of the socket. However according to the TCP specification the OS have to keep the lower level tidbits of the socket open for a certain amount of time in order to detect retransmission, and similar. In this particular case it's likely keeping the socket around for a bit in order to detect a reply to the SYN packet sent so it can reply more sensibly and not mix up the reply with further packets sent.

    0 讨论(0)
  • 2021-02-05 23:05

    You're calling *Begin*Connect - so doing it asynchronously. You're quite possibly trying to close the socket before it's even connected - so when it then connects, it remains open.

    Try connecting synchronously - or closing it in OnSocketConnected so you can see the effect of closing a genuinely connected socket.

    0 讨论(0)
  • 2021-02-05 23:07

    By design, you should always call Shutdown before closing the socket.

    mySocket.Shutdown(SocketShutdown.Both);
    mySocket.Close();
    

    Doing so effectively disables send and receive on the socket, so it will not be accepting incoming data after you've closed it, even if the OS still has control of it.

    Jon Skeet also has a point, that since you're opening the connection asynchronously, it may actually be connecting while you're trying to close it. However, if you call Shutdown on it, it will not allow information to be received as you are experiencing.

    Edit: You can only Shutdown a socket that is already connected, so bear this in mind as you write your code.

    0 讨论(0)
提交回复
热议问题