C# Tcp BeginAcceptTcpClient 抛出 ObjectDisposedException [英] C# Tcp BeginAcceptTcpClient throws ObjectDisposedException

查看:69
本文介绍了C# Tcp BeginAcceptTcpClient 抛出 ObjectDisposedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 UDP 升级到 TCP,但我完全迷失了.:(

I'm trying to upgrade from UDP to TCP, but I am completely lost. :(

这是我的服务器代码(不要太长).

This is my Server code (not too long).

    private readonly TcpListener _tcpListener;

    public TCP(IPEndPoint endPoint)
    {
        try
        {
            _tcpListener = new TcpListener(endPoint);
            _tcpListener.Start();

            AcceptTcpClient();
            AcceptSocket();


            TestClient test = new TestClient();
            test.Connect();
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: " + e);
        }
        finally
        {
            _tcpListener.Stop();
        }
    }

    private void AcceptSocket()
    {
        _tcpListener.BeginAcceptSocket(AcceptIncomingSocket, _tcpListener);
    }
    private void AcceptTcpClient()
    {
        _tcpListener.BeginAcceptTcpClient(AcceptConnection, _tcpListener);
    }
    private void AcceptIncomingSocket(IAsyncResult ar)
    {
        try
        {
            var clientSocket = _tcpListener.EndAcceptSocket(ar);

            Console.WriteLine("Socket accepted: " + clientSocket.Connected);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: " + e);
        }
    }

    private void AcceptConnection(IAsyncResult ar)
    {
        try
        {
            if (ar != null)
            {
                TcpClient client = _tcpListener?.EndAcceptTcpClient(ar);

                Console.WriteLine("Connected. " + (client != null && client.Connected));
                Console.ReadLine();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: " + e);
        }
        catch (ObjectDisposedException e)
        {
            Console.WriteLine("Disposed: " + e);
        }
    }

这是我的客户端代码:

            client = new TcpClient();

            client.Connect("127.0.0.1", 2500);

            if (client.Connected)
            {
                Console.WriteLine("TestClient_Connected");
                Console.ReadLine();
            }

            NetworkStream stream = client.GetStream();

            byte[] toSend = System.Text.Encoding.ASCII.GetBytes("HELLO THERE");

            stream.Write(toSend, 0 , toSend.Length);

            byte[] toSend2 = System.Text.Encoding.ASCII.GetBytes("HELLO 2");

            stream.Write(toSend2, 0, toSend2.Length);


            Console.ReadLine();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

问题是,当我创建客户端实例时,我的服务器不会调用 AcceptConnection,而是调用 AcceptIncomingSocket.之后,当客户端第二次写入时,调用 AcceptConnection 函数,并抛出此异常:(整个控制台输出,因为调试消息)

The problem is, when I create the client instance, my server won't call the AcceptConnection, but instead it calls AcceptIncomingSocket. After that when the client's second write comes in the function AcceptConnection is called, and throws this exception: (Whole console output, because of the debug messages)

TestClient_Connected
Socket accepted: True


Disposed: System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
   at System.Net.Sockets.Socket.EndAccept(Byte[]& buffer, Int32& bytesTransferred, IAsyncResult asyncResult)
   at System.Net.Sockets.TcpListener.EndAcceptTcpClient(IAsyncResult asyncResult)
   at ChallengersDeepDedicated.Server.TCP.AcceptConnection(IAsyncResult ar) ```

推荐答案

我建议你看一下微软的文档,有异步套接字客户端和服务器的很好的例子:

I would recommend you to take a look at the Microsoft docs, there are good examples of asynchronous socket client and server:

服务器:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example

客户端:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

编写套接字客户端-服务器程序可能很棘手.为了获得良好的实施,我建议您深入了解细节并了解它的工作原理以及如何正确使用它.

Writing a socket client-server program could be tricky. For having a good implementation I would recommend you dive into details and learn how it works and how properly use it.

我相信阅读文档会很有用,并且会帮助您理解套接字的概念.

I'm sure going over the docs would be useful and will help you understand the concept of sockets.

阅读后,检查新的高性能 System.IO.Pipelines 库,它为您管理缓冲区并让您的生活更轻松:

After reading that, check the new high-performance System.IO.Pipelines library that manages the buffer for you and make your life easier:

https://devblogs.microsoft.com/dotnet/system-io-pipelines-high-performance-io-in-net//#comment-5471

这篇关于C# Tcp BeginAcceptTcpClient 抛出 ObjectDisposedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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