private void ListenerThread() { UdpClient receivingUdpClient = new UdpClient(ClientPort); while (true) { try { IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, ClientPort); // Blocks until a message returns on this socket from a remote host. Byte[] receiveBytes = receivingUdpClient.Receive(ref remoteIpEndPoint); NetCommand cmd = NetCommand.Parse(receiveBytes); IPAddress sender = remoteIpEndPoint.Address; lock (_incomingQueue) { _incomingQueue.Push(new NetPackage() { NetCommand = cmd, Sender = sender }); Debug.WriteLine($"Queue count: {_incomingQueue.Count}"); } Debug.WriteLine("Network data received!"); if (NetworkEvent != null) { Debug.WriteLine("Invoking event handlers: " + NetworkEvent.GetInvocationList().Length); } else { Debug.WriteLine($"No event handlers attached! Read from queue manually"); } NetworkEvent?.Invoke(cmd, sender); } catch (SocketException e) { Debug.WriteLine(e); throw; } } }
public void SendCommandMulticast(NetCommand command) { IPAddress localIp = GetSelfIp(); string strIp = localIp.ToString(); int dotIndex = strIp.LastIndexOf('.'); string subnetIp = strIp.Substring(0, dotIndex + 1); int currentIpNumber = Int32.Parse(strIp.Substring(dotIndex + 1, strIp.Length - dotIndex - 1)); for (int i = 0; i < 255; i++) { if (currentIpNumber == i) { continue; } string clientIp = subnetIp + i.ToString(); SendCommand(command, IPAddress.Parse(clientIp)); } }
public void SendCommandMulticast(NetCommand command) { // Not actually multicast, lol. =( // Get all subnet's IPs and send one package to all of them. IPAddress localIp = GetSelfIp(); string strIp = localIp.ToString(); int dotIndex = strIp.LastIndexOf('.'); string subnetIp = strIp.Substring(0, dotIndex + 1); int currentIpNumber = Int32.Parse(strIp.Substring(dotIndex + 1, strIp.Length - dotIndex - 1)); for (int i = 0; i < 255; i++) { if (currentIpNumber == i) { continue; } string clientIp = subnetIp + i.ToString(); SendCommand(command, IPAddress.Parse(clientIp)); } }