networkstream仅将数据发送到连接到服务器的最后一个IP

时间:2013-07-13 08:33:22

标签: c# sockets chat networkstream

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

        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 ..请有人帮我找到错误..所有帮助都将是感谢,提前谢谢!

1 个答案:

答案 0 :(得分:1)

那是因为你在sendData执行了

NetworkStream nStream = tcpClient.GetStream();

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