UDP 网络通信 C#
2016-04-29 10:38
531 查看
接收端
发送端
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace UDPReceiveTest { public partial class Form1 : Form { public UdpClient udpClient; public Thread UdpThread; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { if (UdpThread != null) { UdpThread.Abort(); Thread.Sleep(TimeSpan.FromMilliseconds(500d)); } System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; if (udpClient != null) { UdpThread.Abort(); Thread.Sleep(TimeSpan.FromMilliseconds(500d)); udpClient.Close(); } try { udpClient = new UdpClient(int.Parse(txtPort.Text)); UdpThread = new Thread(new ThreadStart(UdpReciveThread)); UdpThread.Start(); } catch (Exception y) { MessageBox.Show(this, y.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error); this.Dispose(true); } } private void button1_Click(object sender, EventArgs e) { txtMessage.Text = string.Empty; } delegate void SetTextCallback(IPEndPoint remoteHost, byte[] buf, string bufs); //接收数据线程 void UdpReciveThread() { IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName); IPEndPoint remoteHost = new IPEndPoint(IPAddress.Any, 0); while (udpClient != null &&Thread.CurrentThread.ThreadState.Equals(ThreadState.Running)) { try { byte[] buf = udpClient.Receive(ref remoteHost); string bufs = Encoding.UTF8.GetString(buf); txtMessage.Text += remoteHost.Address.ToString() + "说:" +Environment.NewLine; txtMessage.Text += bufs + Environment.NewLine; } catch (Exception y) { } } txtMessage.Text += "结束..." + (char)13; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { udpClient.Close(); UdpThread.Abort(); } catch { } } } }
发送端
using System; using System.Net.Sockets; using System.Text; using System.Windows.Forms; namespace UDPSendTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSend_Click(object sender, EventArgs e) { try { UdpClient uc = new UdpClient(txtIP.Text, int.Parse(txtPort.Text)); byte[] sendbuf = Encoding.UTF8.GetBytes(txtMessage.Text); uc.Send(sendbuf, sendbuf.Length); } catch (Exception y) { MessageBox.Show(this, y.Message, "发送失败", MessageBoxButtons.OK,MessageBoxIcon.Hand); } } } }
相关文章推荐
- UDP SOCKET网络通信 C#
- HTTP权威指南读书笔记(一)HTTP概述、URL和资源及报文详解
- IOS SCNetworkReachability和Reachability监测网络连接状态
- IOS安装包分发(windows+tomcat+私有证书https)
- Ambiguous handler methods mapped for HTTP path
- 4月全球域名商新增注册量21强:厦门点媒网络上榜
- HTTP head 详解 (转)
- 常见的网络设备
- 深度卷积网络CNN与图像语义分割
- http服务跟踪及调试工具
- Android中检测手机制式和移动网络类型
- 使用C#的HttpWebRequest模拟登陆网站
- TCP连接的三次握手和四次挥手
- XMLHttpRequest 对象
- OSI 参考模型与TCP/IP 参考模型的比较
- (转)OKhttp封装
- 区块链网络动力学对世界的解构和重构
- OSI七层模型与TCP/IP五层模型
- Android中请求网络
- HTTP知识点总结