[英]closing sockets in asynchronous sockets
I have developed server listening to multiple clients using asynchronous sockets. 我已经开发了使用异步套接字侦听多个客户端的服务器。 I have used the following method for stopping server from listening to clients. 我使用以下方法阻止服务器监听客户端。
//Button 2 -- To Stop Server
private void button2_Click(object sender, EventArgs e)
{
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
socket.Dispose();
}
But problem is that when I restart the server it shows error socket connection in use. 但是问题是,当我重新启动服务器时,它显示使用中的错误套接字连接。 So what is the proper way for closing sockets ans stopping server. 那么关闭套接字和停止服务器的正确方法是什么。 I need to stop the server as soon as I press button in UI. 我需要在按下UI中的按钮后立即停止服务器。
Finally I was able to solve my problem. 终于我能够解决我的问题了。 Using the following code I was able to shutdown server cleanly : - 使用以下代码,我可以干净地关闭服务器:-
private void button2_Click(object sender, EventArgs e)
{
if (active_clients.Count >= 0)
{
// active client is the list of sockets clients were connected before
//server shutdown.
active_clients.ForEach(delegate(Socket s)
{
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (ObjectDisposedException ex)
{
if (ex.InnerException is SocketException)
{
MessageBox.Show("some message");
return;
}
}
s.Close();
});
active_clients.Clear();
}
try
{
serverSocket.Close();
}
catch (Exception)
{
return;
}
}
If you want to shut down your server application you should also close all open client connections. 如果要关闭服务器应用程序,则还应该关闭所有打开的客户端连接。 These are not closed when you close the listening socket (that I assume is the variable socket
). 当您关闭侦听套接字(我认为是变量socket
)时,这些不会关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.