如何“解除绑定"?以编程方式创建套接字? [英] How to "unbind" a socket programmatically?

查看:168
本文介绍了如何“解除绑定"?以编程方式创建套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1)套接字似乎直到进程结束才与LocalEndPoint解除绑定.
2)我尝试了其他问题的解决方案,还尝试等待一分钟-均无济于事.
3)目前,我已经尝试了以下方法来摆脱套接字及其连接:

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)经过一番谷歌搜索之后,我似乎无法解除端口绑定,因此,如果我有足够数量的连接客户端,我最终将用光端口来监听.

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.

推荐答案

我怀疑您将连接的客户端的套接字与服务器套接字混淆了.

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.

更新以消除一些困惑

您应该有一个服务器"套接字,您在该套接字上调用了.Bind(EndPoint),然后调用了.Listen().这是您要关闭/关闭以解除绑定"并释放端口以供以后使用的套接字.

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:

  • 关机
  • 关闭
  • 从您的列表中删除

断开连接,其余的都是不必要的.

Disconnect and the rest are unnecessary.

这篇关于如何“解除绑定"?以编程方式创建套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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