Udp通讯实例
2010-04-27 15:01
225 查看
代码
namespace MyUdpClient { public partial class FrmUdpClient : Form { private Thread thread1; private UdpClient udpSend; private UdpClient udpReceive; public FrmUdpClient() { InitializeComponent(); } private void FrmUdpClient_Load(object sender, EventArgs e) { thread1 = new Thread(new ThreadStart(ReceiveMessage)); thread1.Start(); } private void ReceiveMessage() { byte[] bytes = null; //在本机制定和的端口连接 udpReceive = new UdpClient(8001); //将套接字加入广播组 udpReceive.JoinMulticastGroup(IPAddress.Parse("224.100.0.10"), 50); //接收从远程发送来的消息 IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); while (true) { //ref表示引用类型的IPPoint实例接受消息 try { bytes = udpReceive.Receive(ref iep); } catch (Exception ex) { MessageBox.Show("接收消息错误!"); return; } finally { } string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (str == "") { MessageBox.Show("接收消息错误!"); return; } string msg = "来自" + iep.ToString() + "的消息"; //显示消息并以message 为消息的标题 DialogResult result = MessageBox.Show(str, msg); } } private void FrmUdpClient_FormClosed(object sender, FormClosedEventArgs e) { if (udpSend != null) { udpSend.Close(); } udpReceive.Close(); thread1.Abort(); } private void btnSend_Click(object sender, EventArgs e) { byte[] bytes = null; //如果发送消息为空,则不发送 if (tbxMessage.Text == "") { MessageBox.Show("消息不能为空"); return; } //初始化UdpClient udpSend = new UdpClient(); //实际使用时应将127.0.0.1改为服务器的远程IP IPAddress remoteIPAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIPAddress, 8002); bytes = System.Text.Encoding.UTF8.GetBytes(tbxMessage.Text); //设置重发次数 int retry = 0; //进入发送消息循环 while (true) { //将发送内容转换为字节数组 try { udpSend.Send(bytes, bytes.Length, remoteIPEndPoint); //若成功则退出循环 break; } catch (Exception ex) { if (retry < 3) { //重试次数加1,继续尝试发送 retry++; continue; } else { //如果重试次数大于3次,提示发送失败并跳出循环 DialogResult result = MessageBox.Show("发送失败!" + ex.ToString()); break; } } finally { } } //清空TbxMessage中的内容 tbxMessage.Clear(); //光标还原 tbxMessage.Focus(); udpSend.Close(); } } }
相关文章推荐
- WinSock UDP通讯实例
- UDP通讯实例
- Java基于UDP协议的简单通讯实例
- RAKENT创建UDP实例,RAKNET简单通讯实例
- UDP协议点对点(P2P)通讯(或者说NAT穿越)实例
- UDP通讯实例
- java网络编程之UDP通讯
- AIDL机制实现进程间的通讯实例
- Socket编程 (异步通讯,解决Udp丢包) 4
- 麻雀虽小,五脏俱全-C# 创建windows服务、socket通讯实例
- node.js和socket.io纯js实现的即时通讯实例分享
- JAVA 与 QQ 网络通讯实例
- C#UDP通讯UdpClient
- 《VC网络通讯编程实例》目录
- Android之通过AIDL机制实现进程间的通讯实例
- Socket.io+Nodejs通讯实例---流程梳理
- VC++之网络编程五 聊天编程实例(UDP)
- 自定义的投票协议的通讯(tcp/ip 与 udp示例)
- UDP通讯流程
- TCP/UDP编程实例