C#TcpClient给出ObjectDisposedException

时间:2017-05-21 10:15:05

标签: c# sockets

我有一个非常基本的套接字聊天室(服务器/客户端)。我在服务器中遇到ObjectDisposedException错误。每次客户端连接时,它都会创建一个新线程来处理这个客户端(是的,我知道这可能对大量客户端有问题,但我最多只能有10个)。然后这个线程将循环,每次它将读取连接到客户端的NetworkStream,将其回送给客户端,然后循环。这是代码:

while (true)
{
    buffer = new byte[client.ReceiveBufferSize];

    //Read incoming data
    int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

    string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);

    if (dataReceived == "CONSOLE::close") //if client tells server it is closing, remove client from clients list
    {
        clients.Remove(client);
        client.Close();
        break;
    }
    else //send data to all clients
    {
        byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(dataReceived);

        foreach (TcpClient b in clients)
        {
            NetworkStream x = b.GetStream();
            x.Write(bytesToSend, 0, bytesToSend.Length);
        }
    }
}

客户端是当前客户端连接,客户端是所有当前连接客户端的列表。

我在while循环内的第一行收到错误buffer = new byte[client.ReceiveBufferSize];有关错误的更多详情:

An unhandled exception of type 'System.ObjectDisposedException' occurred in System.dll
Additional information: Cannot access a disposed object.

但这个物品还没被我处理掉?另请注意我使用多个线程,因此不确定这是否会影响它。有人能让我更好地理解为什么会出现这个错误吗?感谢。

修改
这是while循环之前的代码片段(相同的方法):

byte[] buffer;

//Client has connected
client = listener.AcceptTcpClient();
clients.Add(client);

//Create new thread for listening
Thread t = new Thread(new ThreadStart(ClientListener));
t.IsBackground = true;
t.Start();

AppendTextBox("Client has connected" + Environment.NewLine);

//Create network stream to get incoming data
NetworkStream nwStream = client.GetStream();

单击按钮时会调用该方法。

localIP = IPAddress.Parse(SERVER_IP);
listener = new TcpListener(localIP, PORT);
listener.Start();

//Create new thread on which the server listens for clients
Thread t = new Thread(new ThreadStart(ClientListener));
t.IsBackground = true;
t.Start();

SOLUTION:
我是愚蠢的,并没有意识到在本地方法之外初始化client使得所有线程都可以访问它。因此,当一个线程关闭client时,它会关闭它们。感谢Karolis。

0 个答案:

没有答案