UDPLayer.cs
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 TestSeverDemo
{
public delegate bool MessageReceivedEventHandler(ref THMessage th);
public class UDPLayer
{
UdpClient udpcRecv = null;
IPEndPoint localIPep = null;
Thread thrRecv = null;
bool isudpStart = false;
public void StartServer(string ip, int port)
{
if(!isudpStart)
{
localIPep = new IPEndPoint(IPAddress.Parse(ip),port);
udpcRecv = new UdpClient(localIPep);
thrRecv = new Thread(ReceiveMessage);
thrRecv.Start();
isudpStart = true;
Console.WriteLine("UDP server started");
}
}
public void StopServer()
{
if(isudpStart)
{
thrRecv.Abort();
udpcRecv.Close();
isudpStart = false;
Console.WriteLine("UDP server stoped");
}
}
public event MessageReceivedEventHandler MessageHandler;
public void ReceiveMessage()
{
while(isudpStart)
{
try
{
//收到数据
byte[] byteRecev = udpcRecv.Receive(ref localIPep);
THMessage th = new THMessage(byteRecev);
if (MessageHandler(ref th))
{
udpcRecv.Send(th.sendpayload, th.sendpayload.Length, localIPep);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}
}
}