Nidrax

UdpServer.cs

Oct 4th, 2018
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using System.Collections.Concurrent;
  7.  
  8. namespace N
  9. {
  10.     public class Server
  11.     {
  12.         private UdpClient _server;
  13.         private UdpClient _sender;
  14.  
  15.         private readonly int _incoming_port = 32676;
  16.         private readonly int _outgoing_port = 32677;
  17.  
  18.         private bool _stop = false;
  19.         private ConcurrentQueue<byte[]> _buffer;
  20.         private readonly IPEndPoint _endPoint;
  21.  
  22.         public delegate void OnClientConnected();
  23.         public event OnClientConnected ClientConnected;
  24.         public delegate void OnMessageReceived(byte[] msg);
  25.         public event OnMessageReceived MessageReceived;
  26.  
  27.         private static Server _Instance;
  28.         public static Server Instance
  29.         {
  30.             get
  31.             {
  32.                 if (_Instance is null)
  33.                     _Instance = new Server();
  34.                 return _Instance;
  35.             }
  36.         }
  37.  
  38.         private Server()
  39.         {
  40.             _server = new UdpClient(_incoming_port, AddressFamily.InterNetwork);
  41.             _sender = new UdpClient();
  42.             _endPoint = new IPEndPoint(IPAddress.Loopback, _outgoing_port);
  43.         }
  44.  
  45.         public void Run()
  46.         {
  47.             _buffer = new ConcurrentQueue<byte[]>();
  48.             _stop = false;
  49.             Task.Run(() => SendLoop());
  50.             RunReceive();
  51.         }
  52.  
  53.         private void RunReceive()
  54.             => _server.BeginReceive(DoReceive, new object());
  55.  
  56.         public void Send(byte[] message)
  57.         {
  58.             _buffer.Enqueue(message);
  59.         }
  60.  
  61.         private void SendLoop()
  62.         {
  63.             while(!_stop)
  64.             {
  65.                 if (!_buffer.TryDequeue(out byte[] msg)) continue;
  66.  
  67.                 _sender.Send(msg, msg.Count(), _endPoint);            
  68.             }
  69.         }
  70.  
  71.         private void DoReceive(IAsyncResult result)
  72.         {
  73.             IPEndPoint ip = new IPEndPoint(IPAddress.Any, _incoming_port);
  74.             byte[] bytes = _server.EndReceive(result, ref ip);
  75.             MessageReceived?.Invoke(bytes);
  76.             if (!_stop) RunReceive();
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment