QQ群的效果实现
在上一篇的基础上对服务器端进行修改。添加一个类,用来转发客户端发给服务器端的消息。
public class Transform
{
//clientName是用户名,msg是客户端发来的消息,clientList是连接上的所有客户端
public static void PushMessage(String clientName, String msg, Dictionary<String, Socket> clientList)
{
foreach (var item in clientList)
{
Socket tranSocket = (Socket)item.Value;
String msgTemp = null;
Byte[] castBytes = new Byte[4096];
msgTemp = clientName + msg + "\t\t" + DateTime.Now.ToString();
castBytes = Encoding.UTF8.GetBytes(msgTemp);
try
{
tranSocket.Send(castBytes);
}
catch (Exception e)
{
tranSocket.Close();
tranSocket = null;
continue;
}
}
}
}
在监听代码的位置
Socket socket = o as Socket;
Byte[] byteName = new byte[4096];
while (true)
{
try
{
Socket tSocket = socket.Accept();
arrayList.Add(tSocket);
Int32 len = tSocket.Receive(byteName);
string point = Encoding.UTF8.GetString(byteName, 0, len); //改名
//ShowMsg(point + "连接成功!");
//cboIpPort.Items.Add(point);
//cbPort.Text = point;
//this.Username.Items.Add(point);
if (len > -1)
{
Int32 sublen = point.LastIndexOf("$");
if (tSocket != null && tSocket.Connected)
{
if (sublen > -1)
{
point = point.Substring(0, sublen);
cbPort.Items.Add(point);
if (!dic.ContainsKey(point))
{
dic.Add(point, tSocket);
BroadCast.PushMessage(point ,"上线", false, dic);
txtLog.Text += point + "连接上了服务器\r" + DateTime.Now + "\r\n";
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(tSocket);
}
}
}
}
}
catch (Exception ex)
{
ShowMsg(ex.Message);
break;
}
}
之后在接收信息的位置添加代码
BroadCast.PushMessage(null, words, dic); //名字的位置写成null是因为在客户端的发送消息方法里面,将名字和消息一起保存到
//buffer里面并发送给服务器端。