c#UDP发送接收消息
UDP作为一种简单的、面向数据报的无连接的协议,虽然提供的是不可靠的服务,但是从速度上、一对多传输方面比TCP有着很大的优势。本文主要讲解UDP信息的发送和接收。
Demo界面图如下:
首先打开程序exe文件开启“接收”的服务,然后再次启动程序,输入信息,即可发送信息了,效果图如下:
细心的人会发现,我在接受消息时,已经把接收到的每一个字符的ASCII码的十进制值给打印出来了,这是为了区别Encoding.Default和Encoding.Unicode编码方式的区别。
如下面的小例子:
用Encoding.Default方式进行编码
string message = "hello";byte[] sendbytes = Encoding.Default.GetBytes(message);for (int i = 0; i < sendbytes.Length; i++){ShwMsgForView.ShwMsgforView(listBox, string.Format("{0}", sendbytes[i].ToString()));}ShwMsgForView.ShwMsgforView(listBox, "发送消息:" + message);return; 输出的结果为:
用Encoding.Unicode方式进行编码
string message = "hello";//byte[] sendbytes = Encoding.Default.GetBytes(message);byte[] sendbytes = Encoding.Unicode.GetBytes(message);for (int i = 0; i < sendbytes.Length; i++){ShwMsgForView.ShwMsgforView(listBox, string.Format("{0}", sendbytes[i].ToString()));}ShwMsgForView.ShwMsgforView(listBox, "发送消息:" + message);return;输出的结果为:
结果一目了然,如果使用Encoding.Unicode编码方式对字符串进行编码的话,会自动的在每一个字符后面加一个0,这是因为在字符串转换到字节数组的过程中,Encoding.Default 会将每个单字节字符,如半角英文,转换成一个字节;而把每个双字节字符,如汉字,转换成2个字节。而 Encoding.Unicode 则会将它们都转换成两个字节。因为和我们进行数据通信的终端基本都会传输ASCII码值,而不会进行Unicode编码所以,我采用的Default编码方式。 下面为系统代码:
public Main(){InitializeComponent();systemLog = new BusinessLogicLayer.SystemLog();IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());txtlocalIp.Text = ips[1].ToString();int port = 51888;txtlocalPort.Text = port.ToString();txtSndtoIP.Text = ips[1].ToString();txtSndtoPort.Text = port.ToString();chkbxAnonymous.Checked = true;btnStop.Enabled = false;}
这里我在获取本机IP地址时用的是ips[1].ToString(),发现很多都是用ips[0].ToString()。经过调试发现,ips[0].ToString()为IPV6的地址,而ips[1].ToString()才是IPV4的地址。如下图:
调试图
CMD查看ipconfig图
发送信息类代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.Windows.Forms;namespace BusinessLogicLayer {public class SendMessage{private static UdpClient sendUdpClient;private static string sendIP;private static string sendToPort;private static ListBox listBox;private static SystemLog systemLog = new SystemLog();#region 发送消息/// <summary>/// 发送消息/// </summary>/// <param name="sendMsg"></param>/// <param name="sendIp"></param>/// <param name="sendPort"></param>public static void SendMsgStart(string sendMsg, string sendIp, string sendPort, ListBox listbox){//给参数赋值sendIP = sendIp;sendToPort = sendPort;listBox = listbox;//选择发送模式//固定为匿名模式(套接字绑定的端口由系统自动分配)sendUdpClient = new UdpClient(0);//启动发送线程Thread threadSend = new Thread(SendMessages);threadSend.IsBackground = true;threadSend.Start(sendMsg);//显示状态ShwMsgForView.ShwMsgforView(listBox, "发送线程启动");//将数据存入数据库systemLog.SaveSystemLog("", "发送线程启动", "管理员");}private static void SendMessages(object obj){string message = (string)obj;//byte[] sendbytes = Encoding.Unicode.GetBytes(message);//使用Default编码,如果使用Unicode编码的话,每个字符中间都会有个0,影响解码byte[] sendbytes = Encoding.Default.GetBytes(message);IPAddress remoteIp = IPAddress.Parse(sendIP);IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIp, int.Parse(sendToPort));sendUdpClient.Send(sendbytes, sendbytes.Length, remoteIPEndPoint);sendUdpClient.Close();ShwMsgForView.ShwMsgforView(listBox, "发送消息:" + message);systemLog.SaveSystemLog("", "发送消息,目标:" + remoteIPEndPoint + ",消息内容为:" + message + "", "管理员");}#endregion} }
接受消息类代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.Windows.Forms;namespace BusinessLogicLayer {public class ReceiveMessage{private static UdpClient receiveUdpClient;private static ListBox listBox;private static SystemLog systemLog = new SystemLog();#region 接受消息public static void ReceiveStart(string localip,string localPort,ListBox listbox){listBox = listbox;//创建接受套接字IPAddress localIP = IPAddress.Parse(localip);IPEndPoint localIPEndPoint = new IPEndPoint(localIP, int.Parse(localPort));receiveUdpClient = new UdpClient(localIPEndPoint);//启动接受线程Thread threadReceive = new Thread(ReceiveMessages);threadReceive.IsBackground = true;threadReceive.Start();//显示状态ShwMsgForView.ShwMsgforView(listBox, "接受线程启动");//将数据存入数据库systemLog.SaveSystemLog("", "接受线程启动", "管理员");}private static void ReceiveMessages(){IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);while (true){try{//关闭receiveUdpClient时此句会产生异常byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint);for (int i = 0; i < receiveBytes.Length; i++){ShwMsgForView.ShwMsgforView(listBox, string.Format("{0}[{1}]", remoteIPEndPoint, receiveBytes[i].ToString()));}// string message = Encoding.Unicode.GetString(receiveBytes, 0, receiveBytes.Length);string message = Encoding.ASCII.GetString(receiveBytes, 0, receiveBytes.Length);//显示接受到的消息内容ShwMsgForView.ShwMsgforView(listBox, string.Format("{0}[{1}]", remoteIPEndPoint, message));}catch {break;}}}public static void CloseReceiveUdpClient(){receiveUdpClient.Close();ShwMsgForView.ShwMsgforView(listBox, "接收线程停止");systemLog.SaveSystemLog("", "接收线程停止", "管理员");}#endregion} }
显示消息类代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms;namespace BusinessLogicLayer {public class ShwMsgForView{delegate void ShwMsgforViewCallBack(ListBox listbox, string text);public static void ShwMsgforView(ListBox listbox, string text){if (listbox.InvokeRequired){ShwMsgforViewCallBack shwMsgforViewCallBack = ShwMsgforView;listbox.Invoke(shwMsgforViewCallBack, new object[] { listbox, text });}else{listbox.Items.Add(text);listbox.SelectedIndex = listbox.Items.Count - 1;listbox.ClearSelected();}}} }
至此UDP发送和接收消息搞定,下篇文章分享下使用TCP传输文件。
转载于:https://www.cnblogs.com/bianlan/archive/2012/08/09/2631101.html
c#UDP发送接收消息相关推荐
- ActiveMQ 部署及发送接收消息
ActiveMQ 部署及发送接收消息 一. 下载 下载地址:http://activemq.apache.org/ 我这里使用的版本为当前最新5.8.0. 下载版本有Windows ...
- 【Spring】使用Spring和AMQP发送接收消息(下)
为什么80%的码农都做不了架构师?>>> 上篇讲了RabbitMQ连接工厂的作用是用来创建RabbitMQ的连接,本篇就来讲讲RabbitMQ的发送消息.通过RabbitMQ发 ...
- JavaWeb聊天(Redis+环信) 一、发送接收消息、聊天记录拉取
公司有需求做一个聊天功能. APP端,跟网页端互相聊天 android端直接嵌入了环信提供的DEMO.聊天记录.都是存储在本地自己进行维护. 所以本次只需要维护网页端的聊天记录~还有接收发送的消息就好 ...
- 韩顺平Java:qq项目离线发送接收消息/文件扩展
思路:1.在服务端创建一个ConcurrentHashMap线程安全的集合用来存储离线用户的消息和文件,为了实现每个用户可以保存多条离线消息,我们在键值对value中采用ArrayList来保存多条m ...
- html消息发送接收,在html页面中 如何应用mqtt协议发送/接收消息
经过前面几篇文章的介绍,在很多场景下利用NodeMCU加持mqtt协议来控制几乎所有需要传感器监控的行业都能极大地简化物联的成本.在这样一个基础上,还能拓展出很多好玩的.实际运用的甚至能够作为商业化运 ...
- 怎样用python模拟微信扫码登录_十一、模拟扫码登录微信(用Django简单的布置了下页面)发送接收消息...
importreimporttimeimportjsonimportrequestsfrom bs4 importBeautifulSoupfrom django.shortcuts importre ...
- linux下使用UDP发送接收数据
//接收 static int sock_fd; struct sockaddr_in recv_addr; //读取参数 struct sockaddr_in send_addr; //发送参数 s ...
- C#-发送接收消息MQ
项目需要接收到MQ推送消息,记录一下 链接:https://pan.baidu.com/s/1ggMbysb 密码:nuwh 转载于:https://www.cnblogs.com/nanxiuyon ...
- matlab发送mavlink消息
主要介绍了通过matlab脚本实现UDP发送mavlink消息,为后面matlab计算,与Optitrack联合调试,控制无人机做准备. 示例演示效果链接为 matlab通过UDP协议发送mavlin ...
最新文章
- 新春祝福必杀计之发送短信攻略
- HBase Java API 创建表时一直卡住
- 树莓派 rfid_树莓派工控机做Modbus RTU主站读取RFID数据
- 基于Modbus RTU协议的开关量控制采集简介
- 随机化快速排序+快速选择 复杂度证明+运行测试
- 理解Windows窗体和WPF中的跨线程调用
- 数据库MySQL基础---DDL/DML/DQL
- centos7安装Nginx 配置及反向代理
- MATLAB R2022a for Mac(专业编程和数学计算软件)
- JavaScript性能优化之加载与执行
- 回溯____蓝桥 棋盘
- 有道智云 php,有道智云编辑器 Android SDK
- 无限级分类处理成树形结构
- 超低功耗CMOS 16Mbit SRAM
- 华硕路由器远程代码执行漏洞通告
- 芒果不能用百度了,怎么办?
- elementUI脚手架
- win7怎么设置计算机的性能,win7怎么提升电脑性能
- 12款个人防火墙软件横向评测
- Color2Gray: Salience-Preserving Color Removal实现
热门文章
- 测试网内主机存活状态
- [转] Mac os x 使用ftp
- IBM收购National Interest Security
- 关于软件系统维护的一点想法
- K8S 核心组件 kubelet 与 kube-proxy 分析
- [圣诞记]HULK七周年庆
- 一场360容器圈的武林大会“360互联网技术训练营第九期—360容器技术解密与实践” (附PPT与视频)
- File对象的深度遍历以及删除练习。
- 统计一个长度为2的子字符串在另一个字符串中出现的次数.例如:假定输入的字符串为“asd asasdfg asd as zx67 asd mklo”,子字符串为“as”,函数返回值为6。
- 浅谈分布式和微服务架构