C# 使用套接字的客户机-服务器连接

C# 使用套接字的客户机-服务器连接,c#,sockets,tcp,C#,Sockets,Tcp,我有一个程序,多个客户端可以使用套接字连接到服务器: private void performConnect() { while (true) { if (myList.Pending()) { thrd = thrd + 1; tcpClient = myList.AcceptTcpClient(); IPEndPoint ipEndPoint = (IPEndPoint)

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

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。。请有人指出我的错误!非常感谢您的帮助。

请看以下几行:

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();
您正在创建一个新套接字,但将数据发送到存储在全局变量
tcpClient
中的套接字(因为它未在方法中定义),因此完全忽略从组合框解析的IPEndPoint


您不应该为了向客户端发送数据而创建新套接字。相反,将所有客户机存储在一个集合中,并根据组合框的输入检索相应的客户机。

编辑标题,使其与问题描述的第一行不同。好的,将其封装为所问问题。