C#使用UdpClient发送和接收UDP数据示例 16进制与字符串互转 - CSDN博客 http://blog.csdn.net/xuehuic/article/details/53812647
1.服务器
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Server(10086);
- }
-
-
-
-
-
- static void Server(int port)
- {
- try
- {
- UdpClient udpclient = new UdpClient(port);
- while (true)
- {
- IPEndPoint ipendpoint = null;
- byte[] bytes = udpclient.Receive(ref ipendpoint);
- string data = Encoding.Default.GetString(bytes, 0, bytes.Length);
-
- Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2}):{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
- }
- udpclient.Close();
- }
- catch (Exception ex)
- {
- Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
- }
- Console.ReadKey();
- }
- }
- }
2.客户端
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Client("127.0.0.1", 10086, "play");
- }
-
-
-
-
-
-
-
- static void Client(string ip, int port, string message)
- {
- try
- {
- UdpClient udpclient = new UdpClient();
- IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(ip), port);
- byte[] data = Encoding.Default.GetBytes(message);
- udpclient.Send(data, data.Length, ipendpoint);
- udpclient.Close();
-
- Console.WriteLine("{0:HH:mm:ss}->发送数据(to {1}):{2}", DateTime.Now, ip, message);
- }
- catch (Exception ex)
- {
- Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
- }
- Console.ReadKey();
- }
- }
- }
3. 字符串转16进制,然后直接发送16进制。
- public static byte[] HexStringToByteArray(string s)
- {
- if (s.Length = 0)
- throw new Exception("将16进制字符串转换成字节数组时出错,错误信息:被转换的字符串长度为0。");
- s = s.Replace(" ", "");
- byte[] buffer = new byte[s.Length / 2];
- for (int i = 0; i < s.Length; i += 2)
- buffer[i / 2] = Convert.ToByte(s.Substring(i, 2), 16);
- return buffer;
- }
4.16进制转字符串,接收端用于识别显示
-
-
-
-
-
- public static string ByteArrayToHexStringNoBlank(byte[] data)
- {
- StringBuilder sb = new StringBuilder(data.Length * 3);
- foreach (byte b in data)
- sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
- return sb.ToString().ToUpper();
- }
文章来源: dujiahei.blog.csdn.net,作者:dujiahei,版权归原作者所有,如需转载,请联系作者。
原文链接:dujiahei.blog.csdn.net/article/details/78388201
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
评论(0)