首页 > 解决方案 > C# TCP 套接字在失去连接后重新绑定和监听

问题描述

我有一个简单的 TCP 套接字,可以将图像发送到连接的客户端。但是,如果客户端断开连接,我会得到一个异常(我应该这样做):

Systems.Net.SocketException

如果连接丢失,如何重新绑定到 Socket,因此在断开连接后服务器会在客户端断开连接后再次开始侦听?

这是我的源代码,希望有人可以帮助我。

static void HandleServer()
        {
            int sent;
            Console.WriteLine("Server is starting...");
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

            Socket newsock = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream, ProtocolType.Tcp);

            newsock.Bind(ipep);
            newsock.Listen(10);
            Console.WriteLine("Waiting for a client...");

            Socket client = newsock.Accept();
            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Client {0} connected at port {1}!",
                            newclient.Address, newclient.Port);


            while(true)
            {
                 //send some data

            }
        }

标签: c#

解决方案


基本上套接字连接是第一次侦听然后第二次检测的问题。任何接受的连接都会到达您的套接字,您可以分离此连接并继续侦听。


推荐阅读