How to “unbind” a socket programmatically?

那年仲夏 提交于 2019-12-06 09:32:13

问题


1) The socket doesn't seem to unbind from the LocalEndPoint until the process ends.
2) I have tried the solutions from the other question, and also tried waiting a minute - to no avail.
3) At the moment I have tried the below to get rid of the socket and its connections:

public static void killUser(User victim)  
    {  
        LingerOption lo = new LingerOption(false, 0);  
victim.connectedSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Linger,     lo);  
        victim.connectedSocket.Shutdown(SocketShutdown.Both);  
        victim.connectedSocket.Disconnect(true);  
        victim.connectedSocket.Close();  
        clients.RemoveAt(victim.ID);  
    }  

4) After a bit of googling, I can't seem to be able to unbind a port, thus if I have a sufficient amount of connecting clients, I will eventually run out of ports to listen on.


回答1:


I suspect you are confusing the sockets of your connected clients with your server socket.

Your server socket is the one listening for incoming connections on a specific port. The socket you close in that function is your pipe to one of (potentially many) remote connections.

To "unbind the port", you'll want to Shutdown/Close the server socket.

Update to clear some confusion

You should have a "server" socket that you made a call to .Bind(EndPoint) on, followed by a call to .Listen(). This is the socket you want to Shutdown/Close to "unbind" and free up a port for later.

You then have multiple "client" sockets that you get references to whenever your "server" socket accepts a new connection. These can all be bound to the same port without problem. To close one of these connections and disconnect your client, do what you're doing now. You can actually trim the method down to:

  • Shutdown
  • Close
  • Remove from your list

Disconnect and the rest are unnecessary.



来源:https://stackoverflow.com/questions/4623045/how-to-unbind-a-socket-programmatically

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