forked from powerfun/udpservice
81 lines
2.6 KiB
C#
81 lines
2.6 KiB
C#
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, MsgModel, IService> action)
|
||
{
|
||
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 = Newtonsoft.Json.JsonConvert.DeserializeObject<MsgModel>(returnData);
|
||
|
||
//lock (locker)
|
||
{
|
||
#if DEBUG
|
||
WriteLine($"本次接收:{ remoteIpEndPoint.Address.ToString() }:{ remoteIpEndPoint.Port }收到消息:{ returnData }");
|
||
#endif
|
||
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);
|
||
}
|
||
}
|
||
}
|