/* here when we receive a udp message the server will split its contents and depending on the contents it will assign * the values in the message to the players stored in a data dictionary * also it reads the message sent */ public static void ReceiveUDPCallBack(IAsyncResult ar) { UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u; IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; UdpState state = new UdpState(); state.e = e; state.u = u; Byte[] receiveBytes = u.EndReceive(ar, ref e); string receiveString = Encoding.ASCII.GetString(receiveBytes); Console.WriteLine("Received UDP : {0}", receiveString); if (receiveString.IndexOf(":") > -1) { char seperator = ':'; string[] strings = receiveString.Split(seperator); if (strings[1] == "MOVE") { foreach (KeyValuePair <int, Player> entry in Players) { if (strings[0] == entry.Value.playerName) { //float posx = float.Parse(); entry.Value.endpoint = e; entry.Value.playerPosX = strings[2]; entry.Value.playerPosY = strings[3]; entry.Value.playerLap = strings[4]; entry.Value.rotation = strings[5]; } } } if (strings[0] == "RESET") { foreach (KeyValuePair <int, Player> entry in Players) { } } // send the positionbroadcasts to everyone in the game so they know of everyone in the server foreach (KeyValuePair <int, Player> entry in Players) { //Echo the data back to the client. if (entry.Value.endpoint != null) { UdpSendMessage(entry.Value.endpoint, receiveString); //Send(handler, content); } } messageReceived = true; u.BeginReceive(new AsyncCallback(ReceiveUDPCallBack), state); } }
public static void UDP_ReceiveMessages() { // Receive a message and write it to the console. IPEndPoint e = new IPEndPoint(IPAddress.Any, UDP_localPort); UdpClient u = new UdpClient(e); UdpState s = new UdpState(); u.EnableBroadcast = true; s.e = e; s.u = u; Console.WriteLine("listening for messages"); u.BeginReceive(new AsyncCallback(UDP_ReceiveCallback), s); }
public static void UDPReceiveMessages() { IPEndPoint e = new IPEndPoint(IPAddress.Any, 10000); UdpClient u = new UdpClient(e); UdpState s = new UdpState(); s.e = e; s.u = u; Console.WriteLine("Listening for messages"); u.BeginReceive(new AsyncCallback(ReceiveUDPCallBack), s); while (!messageReceived) { } }