c# - 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
}
}
解决方案
基本上套接字连接是第一次侦听然后第二次检测的问题。任何接受的连接都会到达您的套接字,您可以分离此连接并继续侦听。
推荐阅读
- java - 使用 Maven 插件的 Netbeans 中的 Java SSL handshake_failure 错误
- api - Financial Modeling Prep API 是否有速率限制?
- python - 测试返回 JsonReponse 的基于类的 Django 视图
- web - Heroku 部署
- gatsby - 更新 Prismic CMS 内容时在 gatsby 网站上显示新内容
- blazor - 为什么不改变变量的值
- pycharm - 现在强制 lsyncd 到 sybc
- google-cloud-platform - 有什么方法可以从 Windows 中的 powershell 打开 google cloud shell
- c++ - UE4 - 如何在给定 4 个屏幕坐标的情况下缩放纹理或材质?
- spring-integration - Spring 集成 Java DSL 示例