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));
……
}
...全文
504 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zlh0831 2012-08-24
  • 打赏
  • 举报
回复
能够发一下全部教程的链接吗?
ruan_xiao 2010-03-23
  • 打赏
  • 举报
回复
谢谢。。。努力学习。
luo807222676 2010-01-02
  • 打赏
  • 举报
回复
不太明白!
haizhixing126 2009-03-03
  • 打赏
  • 举报
回复
歼击机
haizhixing126 2009-03-03
  • 打赏
  • 举报
回复
支持分享
beniao277 2009-01-23
  • 打赏
  • 举报
回复
路过。
zlb789 2009-01-23
  • 打赏
  • 举报
回复
学习
homejiji 2009-01-23
  • 打赏
  • 举报
回复
支持分享!!!

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧