C#局域网聊天工具制作系列讲座(5)_UDP收发消息
zx022 2009-01-22 11:39:55 由于消息传输要求较低,而且为了简化聊天的步骤,在局域网聊天中,采用UDP是非常好的选择.因为UDP可以不用连接,在获取用户列表后,直接点击用户名就可以发送消息,减少了等待连接等繁琐的步骤,很好的满足了聊天的即时性,实时性特点.
著名局域网聊天工具飞鸽,以及即时聊天工具QQ.在消息传输方面都是采用的UDP.
这讲,我将直接把我程序的源代码贴出来,来讲解,发送消息,接受消息的处理.
1.UDP发送信息
namespace XChat.SendMes
{
public class MsgSend
{
private UdpClient udp = null;
private int PORT;
private IPEndPoint endP = null;
public MsgSend()
{
this.PORT = 58888;
}
public MsgSend(int port)
{
this.PORT = port;
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="hostName">要发送到的主机名</param>
/// <param name="message">要发送的信息</param>
public void SendMessage(string hostName, string message)
{
this.udp = new UdpClient();
endP = new IPEndPoint(Dns.GetHostEntry(hostName).AddressList[0], PORT);
try
{
//byte[] b = Encoding.ASCII.GetBytes(hostName);
byte[] b = Encoding.UTF8.GetBytes(message);
udp.Send(b, b.Length, endP);
}
catch
{
System.Windows.Forms.MessageBox.Show("发送出错!");
}
finally
{
this.udp.Close();
}
}
}
}
要使用时直接new MsgSend().SendMessage(主机名,消息);
2.UDP接收消息
namespace XChat.SendMes
{
//设置消息到前台的委托
public delegate void SetMessage(string mes);
public class MsgRecive
{
private int PORT;
private UdpClient udp = null;
private Thread recThread = null;
private IPEndPoint ipep = null;
private SetMessage setMes;
public MsgRecive()
{
this.PORT = 58888;
}
public MsgRecive(int port)
{
this.PORT = port;
}
/// <summary>
/// 开启后台接受消息线程
/// </summary>
/// <param name="setMes">传入设置消息的委托</param>
public void StartReciveMsg(SetMessage setMes)
{
this.setMes=setMes;
udp = new UdpClient(PORT);
recThread = new Thread(new ThreadStart(ReciveMsg));
recThread.Start();
}
/// <summary>
/// 关闭后台消息接收线程
/// </summary>
public void CloseReciveMsg()
{
recThread.Abort();
//recThread.Join();
udp.Close();
}
private void ReciveMsg()
{
while (true)
{
//这句很重要,否则CPU很容易100%
Thread.Sleep(500);
byte[] b = udp.Receive(ref ipep);
string message = Encoding.UTF8.GetString(b, 0, b.Length);
this.setMes(message);
}
}
}
}
在前台private MsgRecive mr = null;
public xchatFrm()
{
……
this.mr = new MsgRecive(port);
this.mr.StartReciveMsg(new SetMessage(GetMes));
……
}