private void ListenToUDP() { IPEndPoint local = new IPEndPoint(userIP, receivePort); IPEndPoint remote = new IPEndPoint(IPAddress.Broadcast, sendPort); UdpClient udpReceiver = new UdpClient(local); udpListen = true; while (udpListen) { byte[] message = udpReceiver.Receive(ref remote); string userName = Encoding.UTF8.GetString(message); User newUser = new User(userName, remote.Address, tcpPort); if (Users.Find(x => x.userIP.ToString() == remote.Address.ToString()) == null && userIP.ToString() != remote.Address.ToString()) { newUser.Connect(); Message tcpMessage = new Message((int)TMessage.Connect, this.userName); newUser.SendMessage(tcpMessage); lock (locker) { Users.Add(newUser); } Task.Run(() => ListenUser(newUser)); synchronizationContext.Post( delegate { AddUserMessage($"{newUser.userName} [{newUser.userIP}] ({DateTime.Now}) joined the chat.\n"); history.Append($"{newUser.userName} [{newUser.userIP}] ({DateTime.Now}) joined the chat.\n"); }, null); } } udpReceiver.Close(); }
private void ListenToUDP() { IPEndPoint localEP = new IPEndPoint(userIP, RECEIVE_PORT); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, SEND_PORT); UdpClient udpReceiver = new UdpClient(localEP); ShouldUDPListen = true; while (ShouldUDPListen) { byte[] message = udpReceiver.Receive(ref remoteEP); string userName = Encoding.UTF8.GetString(message); User newUser = new User(userName, remoteEP.Address, TCP_PORT); if (Users.Find(x => x.userIP.ToString() == remoteEP.Address.ToString()) == null && userIP.ToString() != remoteEP.Address.ToString()) { newUser.Connect(); Message tcpMessage = new Message(NAME_TRANSMISSION, (byte)this.userName.Length, this.userName); newUser.SendMessage(tcpMessage); lock (Connection._locker) { Users.Add(newUser); } Thread thread = new Thread(() => ListenUser(newUser)); thread.Start(); synchronizationContext.Post( delegate { display($"{newUser.userName} [{newUser.userIP}] ({DateTime.Now}) joined the chat.\n"); history.Append($"{newUser.userName} [{newUser.userIP}] ({DateTime.Now}) joined the chat.\n"); }, null); } } udpReceiver.Close(); }