2013-07-13 36 views
0

我有一个程序,多个客户端将能够连接到服务器使用套接字。networkstream只发送数据到最后一个IP连接到服务器

 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

这是因为在sendData执行

NetworkStream nStream = tcpClient.GetStream(); 

其中tcpClient变量存储最近接受的连接。相反,你应该使用你的nStream[]阵列来存储所有连接的流。