c# 使用Socket异步接收UDP数据

2019/7/22 17:56:12 人评论 次浏览 分类:学习教程

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.Script.Serialization;

namespace UDP_DEMO_Recv {

    static class Program {

        static void Main(string[] args) {
            InitUdp_232();

            Console.ReadKey();
        }



        #region UDP_232

        public static void InitUdp_232() {

            try {

                var ip = Expand.GetIp;
                var prot = 5021;

                Log(LogType.Open, "UDP Servise IP." + ip);
                Log(LogType.Open, "UDP Servise Port." + prot);

                //初始化socket
                _svrSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                //绑定端口 
                var iep = new IPEndPoint(IPAddress.Any, prot);

                _svrSock.Bind(iep);

                _tempRemoteEp = iep;

                _recvBuf = new byte[1024];//缓冲大小
                _svrSock.BeginReceiveFrom(_recvBuf, 0, _recvBuf.Length, 0, ref _tempRemoteEp, Receive_232, null);

                Console.ReadKey();

            } catch (Exception ex) {

                Log(LogType.Error, ex.Message);
                Console.ReadKey();
            }

        }

        public static void Receive_232(IAsyncResult ar) {
            try {

                _svrSock.BeginReceiveFrom(_recvBuf, 0, _recvBuf.Length, 0, ref _tempRemoteEp, Receive_232, null);

                //得到客户端发来的 数据,然后怎么把 在把数据回发给可户端
                var cnt = _svrSock.EndReceiveFrom(ar, ref _tempRemoteEp);

                if (cnt <= 0) return;
                var iep = (IPEndPoint)_tempRemoteEp;

                var ip = iep.Address.ToString();
                var port = iep.Port.ToString();

                Log(LogType.Recv, "IPEndPoint.IP = " + ip);
                Log(LogType.Recv, "IPEndPoint.Port = " + port);

                var bufs = _recvBuf.Remove();

                Log(LogType.Recv, BitConverter.ToString(bufs, 0, bufs.Length));

                var udpSend = new UdpClient();

                if (bufs[2] == 0x12 && bufs[3] == 0x01) {
                    // SEND: 5A-3C-12-01-13-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-14-DB
                    // RECV: 5A-3C-16-01-00-00-00-00-00-00-00-00-00-63-CA-35-57-C6-10-06-00-00-00-00-00-96-DB

                    var seq = BitConverter.ToString(bufs, 0, bufs.Length).Replace("-", "").Substring(8, 2);

                    var buf = ("5A-3C-16-01-00-" + seq + "-00-00-00-00-00-00-00-63-CA-35-57-C6-10-06-00-00-00-00-00-96-DB").ToBytes();
                    buf[buf.Length - 2] = buf.Verify();
                    udpSend.Send(buf, buf.Length, new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
                    Log(LogType.Send, BitConverter.ToString(buf, 0, buf.Length));
                }

                if (_recvBuf[2] == 0x12 && _recvBuf[3] == 0x02) {
                    // SEND: 5A-3C-12-02-04-00-00-00-00-00-00-00-00-63-CA-35-57-10-27-00-00-F6-DB
                    // RECV: 5A-3C-1A-02-00-00-00-00-00-00-00-00-00-63-CA-35-57-10-27-00-00-B6-E9-05-00-00-00-00-00-96-DB

                    var seq = BitConverter.ToString(_recvBuf, 0, _recvBuf.Length).Replace("-", "").Substring(8, 2);

                    var buf = ("5A-3C-1A-02-00-" + seq + "-00-00-00-00-00-00-00-63-CA-35-57-10-27-00-00-B6-E9-05-00-00-00-00-00-96-DB").ToBytes();
                    buf[buf.Length - 2] = buf.Verify();
                    udpSend.Send(buf, buf.Length, new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
                    Log(LogType.Send, BitConverter.ToString(buf, 0, buf.Length));
                }

            } catch (Exception ex) {

                Log(LogType.Error, ex.Message);
                Console.ReadKey();
            }

        }

        #endregion

        private static void Log(LogType t, string msg) {
            Console.Write($"{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff} [{t}] { msg}{Environment.NewLine}");
        }

        private enum LogType {
            Open,
            Send,
            Recv,
            Error,
            Info,
        }

    }


    public static class Expand {

        public static string Json(this object o) {
            return new JavaScriptSerializer().Serialize(o);
        }

        public static string GetIp {
            get {
                var localIp = "";
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList) { if (ip.AddressFamily.ToString() == "InterNetwork") localIp = ip.ToString(); }
                return localIp;
            }

        }

        public static byte[] Remove(this byte[] b, byte cut = 0x00) {
            var list = new List<byte>();
            list.AddRange(b);
            for (var i = list.Count - 1; i >= 0; i--) {
                if (list[i] == cut) { list.RemoveAt(i); } else { break; }
            }
            var lastbyte = new byte[list.Count];
            for (var i = 0; i < list.Count; i++) {
                lastbyte[i] = list[i];
            }
            return lastbyte;
        }

        public static string get(this string str, string name) { return str.match("\"" + name + @""":""([^""]+)", 1); }

        public static string getmoney(this string str, string name) { return str.match("\"" + name + @""":""?([\-\d\.]+)", 1); }

        public static string match(this string s, string p, int i = 0) {
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(p)) return string.Empty;
            var match = Regex.Match(s, p);
            if (i < match.Groups.Count) return match.Groups[i].Value;
            i = 0;
            return match.Groups[i].Value;
        }

        public static string ToHexStr(this byte[] b) { return b == null ? string.Join("", b.Select(i => i.ToString("X2"))) : ""; }

        public static string Tomd5Str(this string s) { return string.Join("", MD5.Create().ComputeHash(Encoding.Default.GetBytes(s)).Select(v => v.ToString("x2"))); }

        public static byte[] ToBytes(this string s) {
            s = Replace(s, @"[^\dA-Fa-f]+", "");
            if (s.Length % 2 > 0) s = "0" + s;
            var max = s.Length / 2;
            var buf = new byte[max];
            for (var i = 0; i < max; i++) buf[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
            return buf;
        }

        public static string Replace(this string s, string p, string r) {
            return Regex.Replace(s, p, r);
        }

        /// <summary>
        /// 校验
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        public static byte Verify(this byte[] buff) {
            int len = buff[2];
            byte sum = 0;
            for (int i = 0; i < len; i++) sum = (byte)(sum + buff[i + 3]);
            return sum;
        }
    }


}

 

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->