客户端 - 服务器与套接字的连接

时间:2013-07-13 08:04:40

标签: c# sockets tcp

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

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 :(得分:0)

看看这些内容:

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

您不应创建新套接字以便将数据发送到客户端。而是将所有客户端存储在集合中,并根据组合框的输入检索适当的客户端。