首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我正在尝试关闭udp连接

我正在尝试关闭udp连接
EN

Stack Overflow用户
提问于 2020-12-06 01:45:33
回答 1查看 41关注 0票数 1

在Visual Studio 2019中,我在编写服务器客户端连接时遇到了一个问题。当我调用我的关闭连接时,程序抛出一个break null异常。我尝试了不同的方法注销UDP连接,但都不起作用。

下面是我的代码,它会使客户端出错:

代码语言:javascript
复制
this.clientSocket.SendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer);

当程序在此之后退出时,我的服务器在重新连接时抛出一个套接字异常。

客户端无效

代码语言:javascript
复制
    public void Client_Closing()
    {
        Console.WriteLine("CLOSING SOCKET");

        try
        {
            Console.WriteLine("CLOSING SOCKET");
             
            // Initialise a packet object to store the data to be sent
            Packet sendData = new Packet();
            sendData.ChatDataIdentifier = DataIdentifier.LogOut;
            sendData.ChatName = this.name;
            sendData.ChatMessage = null;
                
            // Get packet as byte array
            byte[] byteData = sendData.GetDataStream();
               
            // Send packet to the server
            this.clientSocket.SendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer);   
              
            // Close the socket
            this.clientSocket.Close();
        }
        catch (Exception ex)
        {
            // MessageBox.Show("Closing Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Console.WriteLine("Closing Error: " + ex.Message);
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2020-12-06 06:15:28

我想通了谢谢你的帮助coder_b

我从一个事件处理程序调用关闭void,该处理程序在客户端关闭时运行。我在一个类的另一个实例上设置了它。

我将事件处理程序实例化到套接字所在的类的同一对象上,它可以工作,这里是固定代码;

代码语言:javascript
复制
                AsynchronousClient AsynchronousClient = new AsynchronousClient();
            AsynchronousClient.StartClient();



            // Some boilerplate to react to close window event, CTRL-C, kill, etc
            //AsynchronousClient h = new AsynchronousClient(); //REMOVED THIS
            _handler += new EventHandler(AsynchronousClient.Handler); //FIXED HERE
            SetConsoleCtrlHandler(_handler, true);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65160041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档