private static void CreateUdpClient(int ListenPort, int id) { UdpState s = new UdpState(); s.e = new IPEndPoint(IPAddress.Any, ListenPort); s.u = new UdpClient(); s.id = id; s.u.Client.ExclusiveAddressUse = false; s.u.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); s.u.Client.Bind(new IPEndPoint(IPAddress.Any, ListenPort)); Debug.WriteLine($"UDP{id}: Listening for messages on port {ListenPort}"); s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s); _udpClients.Add(s.u); }
public static void ReceiveCallback(IAsyncResult ar) { UdpState s = (UdpState)(ar.AsyncState); byte[] receiveBytes = null; try { receiveBytes = s.u.EndReceive(ar, ref s.e); } catch { } try { s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s); } catch { } if (receiveBytes == null) { return; } DataReceived?.Invoke(s.id, Encoding.UTF8.GetString(receiveBytes)); }