日期:2014-05-18  浏览次数:20931 次

TCP/IP多用户通信
想通过TCP实现一个服务器对应多个客户端的通信,现在服务器可以与多台客户机连接,但是只能跟第一个建立连接的客户端发送信息,怎么解决?
服务器代码如下:
//发送信息
 private void button2_Click_1(object sender, EventArgs e)
  {
  try
  {
  Byte[] sendByte = new Byte[64];
  string sendStr = this.textBox1.Text + ":" + this.textBox3.Text + "\r\n";
  sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
  acceptedSocket.Send(sendByte, sendByte.Length, 0);
  }
  catch { }
  }
//建立连接
  private void button1_Click_1(object sender, EventArgs e)
  {
  string ip = textBox4.Text;
  string port = textBox5.Text;
  HostIP = IPAddress.Parse(ip);
  try
  {
  point = new IPEndPoint(HostIP, Int32.Parse(port));
  socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  socket.Bind(point);
  socket.Listen(50);
  acceptedSocket = socket.Accept();
  Thread thread = new Thread(new ThreadStart(Proccess));
  thread.Start();
  }
  catch (Exception ey)
  {
  MessageBox.Show(ey.Message);
  }
  }
客户端与服务器代码类似

------解决方案--------------------
据说要加上while(true)



------解决方案--------------------
C# code

private Dictionary<string, Socket> userlist = new Dictionary<string, Socket>();
while (balive)
                {
                    byte[] buffer = new byte[1024 * 10];
                    soket.Receive(buffer);
                    string msg = Encoding.Unicode.GetString(buffer).TrimEnd('\0');
                    string[] tokens = msg.Split('|');
                    if (tokens[0] == "CONN")
                    {
                        if (this.userlist.ContainsKey(tokens[0]))
                        {
                            break;
                        }
                        else
                        {
                            this.userlist.Add(tokens[1], soket);
                        }
                     }
public void SendMessage(string message, string temp)
        {
            foreach (KeyValuePair<string, Socket> item in userlist)
            {
                    byte[] buffer = Encoding.Unicode.GetBytes(message.ToCharArray());
                    item.Value.Send(buffer);
            }
        }