无法关闭套接字后BeginAccept方法 [英] Cannot Close Socket After BeginAccept Method

查看:132
本文介绍了无法关闭套接字后BeginAccept方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我创建一个套接字,绑定它,开始倾听,然后用beginaccept C#有一个程序!
,但后来当我尝试close\shutdown插座我从beginaccept的AsyncCallback方法例外!

I have a program in c# in which i create a socket, binding it, begin listening and then using beginaccept! but then when I try to close\shutdown the socket I get exceptions from the beginaccept AsyncCallback method!

     private void start_listening()
        {

            main_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iplocal = new IPEndPoint(IPAddress.Any, 11150);
            main_socket.Bind(iplocal);
            main_socket.Listen(5);
            main_socket.BeginAccept(new AsyncCallback(OnClientConnect), null);
          }


        private void Disconnect_Click(object sender, EventArgs e)
        {
            main_socket.Shutdown(SocketShutdown.Both);
            main_socket.Close();
        }

        public void OnClientConnect(IAsyncResult asyn)
        {

            try
            {
                clients[connected_clients] = new Client("CHANGEME", "127.0.0.1", this);
                clients[connected_clients].Socket = main_socket.EndAccept(asyn);
                clients[connected_clients].WaitForData();
                main_socket.BeginAccept(OnClientConnect, null);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
}



非常感谢!

many thanks!

推荐答案

在main_socket被关闭,OnClientConnect()将被调用,但main_socket.EndAccept()应该抛出的ObjectDisposedException。也许你想捕获该异常并把它作为一个监听套接字已关闭的消息。

When main_socket is closed, OnClientConnect() will be called but main_socket.EndAccept() is supposed to throw an ObjectDisposedException. Perhaps you want to catch that exception and treat it as a "The listener socket has been closed" message.

的另外一个问题你的代码是main_socket实际上并没有连接任何东西。调用main_socket.Shutdown()在Disconnect_Click()可能会抛出过,但这次应该是到一个SocketException说,套接字没有连接。我会删除该main_socket.Shutdown()调用。

The other problem with your code is that main_socket is not actually connected to anything. Calling main_socket.Shutdown() in Disconnect_Click() might throw too, but this time it should be a SocketException saying that the socket is not connected. I would remove that main_socket.Shutdown() call.

这篇关于无法关闭套接字后BeginAccept方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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