//--------------------------------------- // SEND //--------------------------------------- public static void SendCallbackUDP(IAsyncResult ar) { //Get a state from the AR UdpState stateUdp = ((UdpState)(ar.AsyncState)); Socket sock = stateUdp.workingSocket; Console.WriteLine(stateUdp.endPoint.Address); int byteSent = sock.EndSendTo(ar); }
public static void ReceiveMessagesUDP(Socket udpSocket) { EndPoint ePoint = new IPEndPoint(IPAddress.Any, 0); UdpClient uClient = new UdpClient((IPEndPoint)ePoint); UdpState stateUdp = new UdpState(); stateUdp.endPoint = (IPEndPoint)ePoint; stateUdp.udpClient = uClient; stateUdp.workingSocket = udpSocket; Console.WriteLine("Listening for messages udp"); //EndPoint ep = new EndPoint(); udpSocket.BeginReceiveFrom(stateUdp.buffer, 0, stateUdp.bufferSize, 0, ref ePoint, new AsyncCallback(ReceiveCallbackUDP), stateUdp); }
//--------------------------------------- // RECEIVE //--------------------------------------- public static void ReceiveCallbackUDP(IAsyncResult ar) { //Start receiving Console.WriteLine("Receiving UDP..."); //Get a state from the AR UdpState stateUdp = ((UdpState)(ar.AsyncState)); //Get main parametres UdpClient uClient = stateUdp.udpClient; Socket sock = stateUdp.workingSocket; //Issue? EndPoint ePoint = stateUdp.endPoint; //EndPoint ePoint = sock.RemoteEndPoint; //Read data into a buffer int receiveBytes = sock.EndReceiveFrom(ar, ref ePoint); stateUdp.endPoint = (IPEndPoint)ePoint; string receiveString = Encoding.ASCII.GetString(((UdpState)ar.AsyncState).buffer); Console.WriteLine("UDP received: {0}", receiveString); //Clear buffer ((UdpState)ar.AsyncState).buffer = new byte[1024]; //Produce content and handle MessageUDP msg = new MessageUDP(); msg.sock = sock; msg.body = receiveString; msg.endPoint = stateUdp.endPoint; producerConsumerUDP.produce(msg); // Begin receive sock.BeginReceiveFrom(stateUdp.buffer, 0, stateUdp.bufferSize, 0, ref ePoint, new AsyncCallback(ReceiveCallbackUDP), stateUdp); }
//SEND TO SESSION MATES public static void SendUDP(String msg, int session) { byte[] byteData = Encoding.ASCII.GetBytes(msg); //Test foreach (Client entry in clientDictionary.Values) { if (entry.raceId != -1 && entry.sessionID == session) { UdpState stateUdp = new UdpState(); stateUdp.workingSocket = entry.udpSocket; stateUdp.endPoint = entry.endPoint; Console.WriteLine("Sending UDP to " + entry.raceId); if (stateUdp != null) { entry.udpSocket.BeginSendTo(byteData, 0, byteData.Length, 0, entry.endPoint, new AsyncCallback(SendCallbackUDP), stateUdp); } } } }