1
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条消息后报错。客户端一旦连接到服务器,无论服务器是否关闭,它都会保持在线状态。如果服务器处于活动状态,它可以接收来自服务器的消息。如果服务器关闭,客户端不会抛出任何异常,而是等待服务器启动。

4

0 回答 0