95 lines
3.2 KiB
C#
95 lines
3.2 KiB
C#
using Assets.Scenes.Ride.Scripts.Model;
|
|
using Assets.Scripts;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Assets.Scenes.Ride.Scripts.Network
|
|
{
|
|
public class UdpService : IService
|
|
{
|
|
private bool isExit = false;
|
|
private UdpClient udpClient;
|
|
private IPEndPoint iPEndPoint;
|
|
|
|
public void Start(Action<List<ReceiveMsgModel>> action)
|
|
{
|
|
if (udpClient == null)
|
|
{
|
|
//if (!IPAddress.TryParse(ConfigHelper.ServerIpAdress, out var ipString))
|
|
//{
|
|
// throw new ArgumentException("IP地址不正确");
|
|
//}
|
|
|
|
//服务端端口
|
|
iPEndPoint = App.UdpAddress;
|
|
udpClient = new UdpClient();
|
|
uint IOC_IN = 0x80000000;
|
|
uint IOC_VENDOR = 0x18000000;
|
|
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
|
|
udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
|
|
udpClient.Client.ReceiveTimeout = 5000;//这里如果不设置超时,会导致整个应用程序阻塞。
|
|
udpClient.Client.SendTimeout = 5000;
|
|
udpClient.Connect(iPEndPoint);
|
|
//heartbeat = new System.Timers.Timer();
|
|
//heartbeat.Interval = 1000;//20秒一次心跳包
|
|
//heartbeat.AutoReset = true;
|
|
//heartbeat.Enabled = true;
|
|
//heartbeat.Elapsed += Heartbeat_Elapsed;
|
|
|
|
Task.Run(async () =>
|
|
{
|
|
while (isExit == false)
|
|
{
|
|
try
|
|
{
|
|
byte[] receiveBytes = udpClient.Receive(ref iPEndPoint);
|
|
var returnData = Encoding.ASCII.GetString(receiveBytes);
|
|
var list = new List<ReceiveMsgModel>();
|
|
var itemList = returnData.Split('|');
|
|
|
|
foreach (var item in itemList)
|
|
{
|
|
var info = ReceiveMsgModel.Parse(item);
|
|
if (info != null)
|
|
{
|
|
list.Add(info);
|
|
}
|
|
}
|
|
action(list);
|
|
}
|
|
catch (SocketException ex)
|
|
{
|
|
await Task.Delay(6000);
|
|
if (isExit == false && udpClient != null)
|
|
{
|
|
udpClient.Connect(iPEndPoint);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
public void Send(byte[] dgram, int bytes)
|
|
{
|
|
udpClient?.Send(dgram, bytes);
|
|
}
|
|
|
|
public void Close()
|
|
{
|
|
isExit = true;
|
|
udpClient?.Close();
|
|
|
|
}
|
|
}
|
|
}
|