Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Net.Sockets;
- using System.Net;
- using System.Collections.Concurrent;
- namespace N
- {
- public class Server
- {
- private UdpClient _server;
- private UdpClient _sender;
- private readonly int _incoming_port = 32676;
- private readonly int _outgoing_port = 32677;
- private bool _stop = false;
- private ConcurrentQueue<byte[]> _buffer;
- private readonly IPEndPoint _endPoint;
- public delegate void OnClientConnected();
- public event OnClientConnected ClientConnected;
- public delegate void OnMessageReceived(byte[] msg);
- public event OnMessageReceived MessageReceived;
- private static Server _Instance;
- public static Server Instance
- {
- get
- {
- if (_Instance is null)
- _Instance = new Server();
- return _Instance;
- }
- }
- private Server()
- {
- _server = new UdpClient(_incoming_port, AddressFamily.InterNetwork);
- _sender = new UdpClient();
- _endPoint = new IPEndPoint(IPAddress.Loopback, _outgoing_port);
- }
- public void Run()
- {
- _buffer = new ConcurrentQueue<byte[]>();
- _stop = false;
- Task.Run(() => SendLoop());
- RunReceive();
- }
- private void RunReceive()
- => _server.BeginReceive(DoReceive, new object());
- public void Send(byte[] message)
- {
- _buffer.Enqueue(message);
- }
- private void SendLoop()
- {
- while(!_stop)
- {
- if (!_buffer.TryDequeue(out byte[] msg)) continue;
- _sender.Send(msg, msg.Count(), _endPoint);
- }
- }
- private void DoReceive(IAsyncResult result)
- {
- IPEndPoint ip = new IPEndPoint(IPAddress.Any, _incoming_port);
- byte[] bytes = _server.EndReceive(result, ref ip);
- MessageReceived?.Invoke(bytes);
- if (!_stop) RunReceive();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment