TcpClient:非连接套接字上不允许该操作。

时间:2012-12-23 21:01:06

标签: c# tcpclient tcplistener

public Server()
    {
        this.tcpListener = new TcpListener(IPAddress.Any, 8000);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        this.tcpListener.Start();
        while (true)
        {
            TcpClient tcpClient = this.tcpListener.AcceptTcpClient();

            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientCommunication));
            clientThread.Start(tcpClient);
        }
    }

    private void HandleClientCommunication(object client)
    {

        if (client != null)
        {
            TcpClient tcpClient = (TcpClient)client;
            clientList.Add(tcpClient);
        }


        foreach (TcpClient tc in clientList)
        {
            if (tc.Available > 0)
            {
                int dataSize = tc.Available;
                Console.WriteLine("Received data from: " + tc.Client.Handle);

                string text = GetNetworkString(tc.GetStream());

                //transmit
                foreach (TcpClient otherClient in clientList)
                {
                    if (tc.Client.Handle != otherClient.Client.Handle)
                    {
                        // The problem is here:
                        Send(otherClient.GetStream(), text);
                    }
                }
            }
        }

    }


    private void Send(NetworkStream ns, string data)
    {
        try
        {
                byte[] Bdata = Encoding.ASCII.GetBytes(data);
                ns.Write(Bdata, 0, Bdata.Length);
                ns.Flush();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }

    }

我得到"非连接套接字上不允许进行操作。"服务器从TcpClient收到3-4条消息后出错。客户端一旦连接到服务器,无论服务器是否关闭,都将保持在线状态。如果服务器处于活动状态,则它可以从服务器接收消息。如果服务器关闭,客户端不会抛出任何异常,而是等待服务器启动。

0 个答案:

没有答案