C# UdpClient 简单记录

最近在使用UDPclient时候总是遇到问题,为了方便后面使用,简单写了一个类,主线程发送 ,新线程接收数据。支持16进制接收以及发送。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace UDP_Client
{
    /// <summary>
    /// 显示UDP接收到的内容
    /// </summary>
    /// <param name="msg"></param>
    public delegate void ShowRecvMsg(string msg,string msg2);
    public class UdpClientClass
    {



        public ShowRecvMsg showRecvMsg; // 定义委托接收到的内容其他类处理
        public bool IsStartUdpRecive;

        UdpClient udpRecvClient;       //接收CLient

        UdpClient udpSendClient;       //发送Client
        Thread Recvthread;//接收线程

        // = new IPEndPoint(IPAddress.Any,0);
        IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 12340);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Msg">发送内容</param>
        /// <param name="RemoteIp">远端IP</param>
        /// <param name="RemotePort">远端端口</param>
        public void UdpSendMsgFuc(string Msg,string RemoteIp,int RemotePort)
        {
            IPAddress iPAddress = IPAddress.Parse(RemoteIp);
            IPEndPoint remotePoint = new IPEndPoint(iPAddress, RemotePort);
            if (udpSendClient != null)
                udpSendClient.Close();
                udpSendClient = new UdpClient();

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Msg.Trim());
            udpSendClient.Send(buffer, buffer.Length, remotePoint);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="RemoteIp"></param>
        /// <param name="RemotePort"></param>
        /// <param name="ishex">是否是16进制发送</param>
        public void UdpSendMsgFuc(string Msg, string RemoteIp, int RemotePort, bool ishex)
        {
            IPAddress iPAddress = IPAddress.Parse(RemoteIp);
            IPEndPoint remotePoint = new IPEndPoint(iPAddress, RemotePort);
            if (udpSendClient != null)
                udpSendClient.Close();
            udpSendClient = new UdpClient();

            if(ishex)
            {
                byte[] buffer = hexStringToBytes(Msg.Trim());
                udpSendClient.Send(buffer, buffer.Length, remotePoint);
            }else
            {
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Msg.Trim());
                udpSendClient.Send(buffer, buffer.Length, remotePoint);
            }

        }

        /// <summary>
        /// 开始接收
        /// </summary>
        public void StartRecvMsg()
        {

            try
            {
                if(Recvthread == null)
                Recvthread = new Thread(Udp_ReceiveFunction);
                IsStartUdpRecive = true;
                Recvthread.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        /// <summary>
        /// 停止接收
        /// </summary>
        public void StopRecvMsg()
        {
            // throw new NotImplementedException();
            try
            {
                if (!Recvthread.IsAlive)
                    Recvthread.Abort();
                IsStartUdpRecive = false;
                Recvthread = null;
          //      Recvthread.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

       public bool IsHexRecv;
        /// <summary>
        /// 接收线程
        /// </summary>
        private  void Udp_ReceiveFunction()
        {
            if(udpRecvClient == null)
               udpRecvClient = new UdpClient(iPEndPoint);
            while (IsStartUdpRecive)
            {
                try
                {
                    byte[] recBuffer = udpRecvClient.Receive(ref iPEndPoint);
                    if (recBuffer != null)
                    {
                        if(IsHexRecv)
                        {
                            string receive = bytetohexstring(recBuffer);
                            showRecvMsg(iPEndPoint.ToString(), receive);
                        }else
                        {
                            string receive = System.Text.Encoding.UTF8.GetString(recBuffer);
                            showRecvMsg(iPEndPoint.ToString(), receive);
                        }

                    }
                }
                catch( Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        /// <summary>
        /// 字符串转16进制Byte
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public byte[] hexStringToBytes(String hexString)
        {

            if (hexString == null || hexString.Equals(""))
            {

                return null;

            }

            hexString = hexString.ToUpper().Replace(" ", "");

            int length = hexString.Length / 2;

            char[] hexChars = hexString.ToCharArray();

            byte[] d = new byte[length];

            for (int i = 0; i < length; i++)
            {

                int pos = i * 2;

                d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

            }
            return d;
        }
        private byte charToByte(char c)
        {

            return (byte)"0123456789ABCDEF".IndexOf(c);

        }
        private string bytetohexstring(byte[] ReceiveBytes)
        {
            //  throw new NotImplementedException();
            string struse = "";

            if (ReceiveBytes != null)
            {
                for (int i = 0; i < ReceiveBytes.Length; i++)
                {
                    struse += string.Format("{0:x}", ReceiveBytes[i]);
                }
            }

            return struse;
        }

    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值