Created
February 23, 2014 20:47
-
-
Save RandomOutput/9177032 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| using System; | |
| using System.Net.Sockets; | |
| using System.Net; | |
| using System.Text; | |
| public class UdpClient : MonoBehaviour { | |
| private static string ip = "192.168.0.0.1"; | |
| private static int port = 9002; | |
| public static bool messageReceived = false; | |
| private struct UdpState { | |
| public UdpClient u; | |
| public IPEndPoint e; | |
| } | |
| // Use this for initialization | |
| void Start () { | |
| } | |
| // Update is called once per frame | |
| void Update () { | |
| } | |
| public static void ReceiveCallback(IAsyncResult ar) | |
| { | |
| UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u; | |
| IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; | |
| Byte[] receiveBytes = u.EndReceive(ar, ref e); | |
| string receiveString = Encoding.ASCII.GetString(receiveBytes); | |
| Console.WriteLine("Received: {0}", receiveString); | |
| messageReceived = true; | |
| } | |
| public static void ReceiveMessages() | |
| { | |
| // Receive a message and write it to the console. | |
| IPEndPoint e = new IPEndPoint(IPAddress.Parse(ip), port); | |
| UdpClient u = new UdpClient(e); | |
| UdpState s = new UdpState(); | |
| s.e = e; | |
| s.u = u; | |
| Console.WriteLine("listening for messages"); | |
| u.BeginReceive(new AsyncCallback(ReceiveCallback), s); | |
| // Do some work while we wait for a message. For this example, | |
| // we'll just sleep | |
| return; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment