如何使用.net4.0停止c#中的侦听套接字?谢谢. [英] How to stop a listening socket in c# with .net4.0 ?Thanks.

查看:469
本文介绍了如何使用.net4.0停止c#中的侦听套接字?谢谢.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用c#的套接字程序.
我正在用异步套接字编写一个简单的聊天室.
这是代码:


I have studying the socket program using c#.
I am writing a simple chatroom with asynchronous socket .
this is code:


...
//creat the listensocket.
this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

this.listenSocket.Bind(localEndPoint);

//Start the server.
listenSocket.Listen(ServerSocketSetting.Backlog);

SocketAsyncEventArgs acceptEventArg = CreateAcceptEventArg();
this.listenSocket.AcceptAsync(acceptEventArg);



我采用以下数学方法来停止listenSocket:



I take the following math to stop the listenSocket:

internal void StopListening()
       {
          //close every client socket first.
           foreach (UserToken item in clientList)
           {
               this.CloseClientSocket(item.receiveSendEnventArg);
           }
           // andthen close the listen socket.
           if (this.listenSocket != null)
           {
               //this.listenSocket.Shutdown(SocketShutdown.Both);
               this.listenSocket.Close();
               //this.listenSocket.Disconnect(true);
           }
       }




当"




Tragedy is occurred when "

this.listenSocket.Close();


时发生悲剧 执行后,聊天室的应用程序将自动关闭.
我本来的想法是停止监听只是不退出应用程序,当用户单击开始监听"时
按钮,它将重新收听.因此,应该有一些我不知道的错误.


" is execeted, the application of the chatroom is close auto.
I original idea is stoping listening only not exit the application, when user click the "start listening"
button , it will to relisten. So, there should have some errors i don''t know.
Thanks for the good man giving me the answer.

推荐答案

此链接的第一件事是关于套接字关闭方法的

http://msdn.microsoft.com/en-us/library/wahsac9k.aspx [ ^ ]

对于面向连接的协议,建议您先调用Shutdown,然后再调用Close方法.这可确保在关闭套接字之前,已在连接的套接字上发送和接收所有数据."

第二件事-不清楚您在CloseClientSocket内部正在做什么.

第三件事-执行if(this.listenSocket!= null)时,还应在操作完成后将其分配为null.

最后一个也是最重要的-应用程序关闭,可能是因为在socket.Close方法执行期间发生了一些异常.您可以尝试将其放入try-catch语句中,并读取错误消息.也许这将有助于定位和修复错误.
First thing this link is about socket Close method

http://msdn.microsoft.com/en-us/library/wahsac9k.aspx[^]

"For connection-oriented protocols, it is recommended that you call Shutdown before calling the Close method. This ensures that all data is sent and received on the connected socket before it is closed."

Second thing - it is not clear what you ar doing inside CloseClientSocket.

Third thing - when you perform if (this.listenSocket != null), you should also assign it to null after opeations are finished.

And the last and most important - application closes, probably, because some exception happens during socket.Close method execution. You could try to place it inside try-catch statement and read an error message. Maybe this will help to locate and fix the error.


这篇关于如何使用.net4.0停止c#中的侦听套接字?谢谢.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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