求救,关于socket侦听
写了个服务器端的Listen,但是当客户端异常关闭的时候(线程被强行终止等),服务器的下次侦听就会产生异常An existing connection was forcibly closed by the remote host。
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint& remoteEP)
at System.Net.Sockets.Socket.ReceiveFrom(Byte[] buffer, EndPoint& remoteEP)
代码如下
private void Listen()
{
try
{
while (flag)
{
int recv = 0;
byte[] data = new byte[1024];
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = sender as EndPoint;
recv = ServerSocket.ReceiveFrom(data, ref tempRemoteEP);
string msgHead = Encoding.Unicode.GetString(data, 0, 4);
}
}
}
请问如何处理这个问题。如果在客户端异常关闭以后让服务器端正常运行。
谢谢各位大大。
------解决方案--------------------sender使用完后要关闭。不关闭资源未释放。
------解决方案--------------------int recv = 0;
byte[] data = new byte[1024];
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = sender as EndPoint;
recv = ServerSocket.ReceiveFrom(data, ref tempRemoteEP); // 估计这句是出错的地方
string msgHead = Encoding.Unicode.GetString(data, 0, 4);
分析一下,发现你没有看看客户端是否可以读数据(比如那时候客户端被终止),就直接开始读取数据,当然会有Exception,只要捕捉SocketException,然后相应处理,就可以了。
------解决方案--------------------记的关闭SOCKET端口
------解决方案--------------------Socket.Close();
Socket.Dispose();
------解决方案--------------------粗犷一点,就直接在
recv = ServerSocket.ReceiveFrom(data, ref tempRemoteEP);