powerfun-new-net/Services/UdpService.cs

93 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<IPEndPoint, ReceiveModel, IService> action, Action<EndPoint> 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<ReceiveModel>(returnData);
//lock (locker)
{
#if DEBUG
WriteLine($"本次接收:{ remoteIpEndPoint.Address.ToString() }:{ remoteIpEndPoint.Port }收到消息:{ returnData }");
#endif
if (msg.CommandType == 1)
{
action(remoteIpEndPoint, JsonConvert.DeserializeObject<MsgModel>(returnData), this);
}
else if (msg.CommandType == 2)
{
action(remoteIpEndPoint, JsonConvert.DeserializeObject<SetClientCommand>(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.Send(dgram, bytes, endPoint);
}
public void Close()
{
_stop = true;
udpServer.Close();
}
void WriteLine(string str)
{
//Debug.WriteLine(str);
}
}
}