为了实现多人聊天,服务器需要存储远程客户端的IP地址和Socket。
用Dictionary存储,IP地址作为Key,Socket作为Value。方便用IP地址索引Socket。
Dictionary<string, Socket> clientDic = new Dictionary<string, Socket>();
当服务器收到客户端连接时,将连接信息存储到上述clientDic中(同时,将IP地址存储到下拉框列表中,便于后续通过下拉框,选择和哪个客户端通信)。
void socketListen()
{
while (true)
{
try
{
clientSocket = server.Accept(); //等待,直到接收到客户端的请求,并为之创建一个负责通信的socket
clientDic.Add(clientSocket.RemoteEndPoint.ToString(), clientSocket);
comboBox1.Items.Add(clientSocket.RemoteEndPoint.ToString());
Thread th = new Thread(socketReceive);
th.IsBackground = true;
th.Start(clientSocket);
}
catch
{
}
}
}
服务器发送消息给客户端时,用下拉框选择客户端的地址,确定和哪个客户端通信。
//服务器给客户端发送消息
private void button1_Click(object sender, EventArgs e)
{
string ip = comboBox1.SelectedItem.ToString(); //获取用户在下拉框中选择的IP地址
clientDic[ip].Send(Encoding.UTF8.GetBytes(writeBox.Text)); //发送消息
showBox.Text += writeBox.Text + "\r\n";
writeBox.Text = "";
}