0

我有一个程序,多个客户端可以使用套接字连接到服务器。

        private void performConnect()
    {

        while (true)
        {
            if (myList.Pending())
            {
                thrd = thrd + 1;
                tcpClient = myList.AcceptTcpClient();

                IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
                string clientIP = ipEndPoint.Address.ToString();
                nStream[thrd] = tcpClient.GetStream();
                currentMsg = "\n New IP client found :" + clientIP;
                recieve[thrd].Start();

                this.Invoke(new rcvData(addNotification));
                try
                {
                    addToIPList(clientIP);

                }
                catch (InvalidOperationException exp)
                {
                    Console.Error.WriteLine(exp.Message);
                }
                Thread.Sleep(1000);
            }

            }



    }

然后服务器可以使用此代码向选定的客户端发送数据(聊天消息)。

        private void sendData(String data)
    {
        IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
        Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
        NetworkStream nStream = tcpClient.GetStream();
        ASCIIEncoding asciidata = new ASCIIEncoding();
        byte[] buffer = asciidata.GetBytes(data);
        if (nStream.CanWrite)
        {
            nStream.Write(buffer, 0, buffer.Length);
            nStream.Flush();
        }
    }

问题是无论我从组合框中选择什么 IP,我发送的消息都将始终定向/发送到连接到服务器的最后一个 IP。请有人帮我找出错误。所有帮助将不胜感激,谢谢提前!

4

1 回答 1

1

那是因为在sendData你表演

NetworkStream nStream = tcpClient.GetStream();

其中tcpClient变量存储最后接受的连接。取而代之的是,您应该使用nStream[]存储所有连接流的数组。

于 2013-07-13T08:39:16.003 回答