using Newtonsoft.Json; using OnlineUserPool.Model; using OnlineUserPool.Unility; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace OnlineUserPool.Services { public class UdpService : IService { private bool _stop = false; //private static IPEndPoint serverIpEndPoint; private static UdpClient udpServer; public UdpService() { //serverIpEndPoint = new IPEndPoint(IPAddress.Parse(ConfigHelp.Ip), ConfigHelp.Port); } public void RunServer(Action action, Action disconnected = null) { udpServer = new UdpClient(ConfigHelp.UdpPort); uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; udpServer.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Task.Run(() => { while (_stop == false) { try { byte[] receiveBytes = udpServer.Receive(ref remoteIpEndPoint); var returnData = Encoding.ASCII.GetString(receiveBytes); var msg = JsonConvert.DeserializeObject(returnData); //lock (locker) { #if DEBUG WriteLine($"本次接收:{ remoteIpEndPoint.Address.ToString() }:{ remoteIpEndPoint.Port }收到消息:{ returnData }"); #endif if (msg.CommandType == 1) { action(remoteIpEndPoint, JsonConvert.DeserializeObject(returnData), this); } else if (msg.CommandType == 2) { action(remoteIpEndPoint, JsonConvert.DeserializeObject(returnData), this); } else { action(remoteIpEndPoint, msg, this); } //if (timer.AutoReset == false) //{ // timer.AutoReset = true; //} } } catch (Exception e) { Serilog.Log.Error("RunServer:" + e.Message); } } }); } public void Send(byte[] dgram, int bytes, IPEndPoint endPoint) { udpServer.SendAsync(dgram, bytes, endPoint); } public void Close() { _stop = true; udpServer.Close(); } void WriteLine(string str) { //Debug.WriteLine(str); } } }