Elight.Utility/Network/UDPHelper.cs

(开头部分) 3KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

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

namespace Elight.Utility.Network
{
    public class UDPHelper
    {
        private bool isStarted = false;
        private bool stop = false;
        private string message;
        private Socket server;
        public delegate void OnMessageReceive(byte[] msg);
        public event OnMessageReceive OnMessageReceived;
        private int port;
        public UDPHelper(int port)
        {
            this.port = port;
        }
        public UDPHelper(string port)
        {
            this.port = Convert.ToInt32(port);
        }
        /// <summary>
        /// 开启服务
        /// </summary>
        public void Start()
        {
            isStarted = true;
            try
            {
                server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                server.Bind(new IPEndPoint(IPAddress.Any, port));//绑定端口号和IP
                new Thread(ReceiveMsg).Start();
            }
            catch
            {
                Stop();
                isStarted = false;
            }
        }


        private void ReceiveMsg()
        {
            while (!stop)
            {
                try
                {
                    //用来保存发送方的ip和端口号
                    byte[] buffer = new byte[1024];
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);
                    int length = server.ReceiveFrom(buffer, ref point);//接收数据报
                    OnMessageReceived?.Invoke(buffer.Take(length).ToArray());
                }
后面还有 59 行代码,解锁后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 算力/个。 规则说明

AI 解读 AI

登录后可用,每次 10 算力,解读结果公开显示在下面。

还没有人解读过这个文件。