Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

simple udp implementation (send/read via mono/c#)

Discussion in 'Multiplayer' started by la1n, Dec 16, 2008.

  1. la1n

    la1n

    Joined:
    Apr 6, 2008
    Posts:
    10
    Two Objects for send and receiving UDP-Packets. Hope this helps. Updated code you will find (german) on our university gamedevelopment page:

    http://www.gametheory.ch/index.jsp?positionId=101139&displayOption=

    la1n

    --------------------------
    UDPReceive.cs
    --------------------------

    Code (csharp):
    1.  
    2. /*
    3.  
    4.     -----------------------
    5.     UDP-Receive (send to)
    6.     -----------------------
    7.     // [url]http://msdn.microsoft.com/de-de/library/bb979228.aspx#ID0E3BAC[/url]
    8.    
    9.    
    10.     // > receive
    11.     // 127.0.0.1 : 8051
    12.    
    13.     // send
    14.     // nc -u 127.0.0.1 8051
    15.  
    16. */
    17. using UnityEngine;
    18. using System.Collections;
    19.  
    20. using System;
    21. using System.Text;
    22. using System.Net;
    23. using System.Net.Sockets;
    24. using System.Threading;
    25.  
    26. public class UDPReceive : MonoBehaviour {
    27.    
    28.     // receiving Thread
    29.     Thread receiveThread;
    30.  
    31.     // udpclient object
    32.     UdpClient client;
    33.  
    34.     // public
    35.     // public string IP = "127.0.0.1"; default local
    36.     public int port; // define > init
    37.  
    38.     // infos
    39.     public string lastReceivedUDPPacket="";
    40.     public string allReceivedUDPPackets=""; // clean up this from time to time!
    41.    
    42.    
    43.     // start from shell
    44.     private static void Main()
    45.     {
    46.        UDPReceive receiveObj=new UDPReceive();
    47.        receiveObj.init();
    48.  
    49.         string text="";
    50.         do
    51.         {
    52.              text = Console.ReadLine();
    53.         }
    54.         while(!text.Equals("exit"));
    55.     }
    56.     // start from unity3d
    57.     public void Start()
    58.     {
    59.        
    60.         init();
    61.     }
    62.    
    63.     // OnGUI
    64.     void OnGUI()
    65.     {
    66.         Rect rectObj=new Rect(40,10,200,400);
    67.             GUIStyle style = new GUIStyle();
    68.                 style.alignment = TextAnchor.UpperLeft;
    69.         GUI.Box(rectObj,"# UDPReceive\n127.0.0.1 "+port+" #\n"
    70.                     + "shell> nc -u 127.0.0.1 : "+port+" \n"
    71.                     + "\nLast Packet: \n"+ lastReceivedUDPPacket
    72.                     + "\n\nAll Messages: \n"+allReceivedUDPPackets
    73.                 ,style);
    74.     }
    75.        
    76.     // init
    77.     private void init()
    78.     {
    79.         // Endpunkt definieren, von dem die Nachrichten gesendet werden.
    80.         print("UDPSend.init()");
    81.        
    82.         // define port
    83.         port = 8051;
    84.  
    85.         // status
    86.         print("Sending to 127.0.0.1 : "+port);
    87.         print("Test-Sending to this Port: nc -u 127.0.0.1  "+port+"");
    88.  
    89.    
    90.         // ----------------------------
    91.         // Abhören
    92.         // ----------------------------
    93.         // Lokalen Endpunkt definieren (wo Nachrichten empfangen werden).
    94.         // Einen neuen Thread für den Empfang eingehender Nachrichten erstellen.
    95.         receiveThread = new Thread(
    96.             new ThreadStart(ReceiveData));
    97.         receiveThread.IsBackground = true;
    98.         receiveThread.Start();
    99.  
    100.     }
    101.  
    102.     // receive thread
    103.     private  void ReceiveData()
    104.     {
    105.  
    106.         client = new UdpClient(port);
    107.         while (true)
    108.         {
    109.  
    110.             try
    111.             {
    112.                 // Bytes empfangen.
    113.                 IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
    114.                 byte[] data = client.Receive(ref anyIP);
    115.  
    116.                 // Bytes mit der UTF8-Kodierung in das Textformat kodieren.
    117.                 string text = Encoding.UTF8.GetString(data);
    118.  
    119.                 // Den abgerufenen Text anzeigen.
    120.                 print(">> " + text);
    121.                
    122.                 // latest UDPpacket
    123.                 lastReceivedUDPPacket=text;
    124.                
    125.                 // ....
    126.                 allReceivedUDPPackets=allReceivedUDPPackets+text;
    127.                
    128.             }
    129.             catch (Exception err)
    130.             {
    131.                 print(err.ToString());
    132.             }
    133.         }
    134.     }
    135.    
    136.     // getLatestUDPPacket
    137.     // cleans up the rest
    138.     public string getLatestUDPPacket()
    139.     {
    140.         allReceivedUDPPackets="";
    141.         return lastReceivedUDPPacket;
    142.     }
    143. }
    144.  

    --------------------------
    UDPSend.cs
    --------------------------

    Code (csharp):
    1.  
    2.  
    3. /*
    4.  
    5.     -----------------------
    6.     UDP-Send
    7.     -----------------------
    8.     // [url]http://msdn.microsoft.com/de-de/library/bb979228.aspx#ID0E3BAC[/url]
    9.    
    10.     // > gesendetes unter
    11.     // 127.0.0.1 : 8050 empfangen
    12.    
    13.     // nc -lu 127.0.0.1 8050
    14.  
    15.         // todo: shutdown thread at the end
    16. */
    17. using UnityEngine;
    18. using System.Collections;
    19.  
    20. using System;
    21. using System.Text;
    22. using System.Net;
    23. using System.Net.Sockets;
    24. using System.Threading;
    25.  
    26. public class UDPSend : MonoBehaviour
    27. {
    28.     private static int localPort;
    29.    
    30.     // prefs
    31.     private string IP;  // define in init
    32.     public int port;  // define in init
    33.    
    34.     // "connection" things
    35.     IPEndPoint remoteEndPoint;
    36.     UdpClient client;
    37.    
    38.     // gui
    39.     string strMessage="";
    40.    
    41.        
    42.     // call it from shell (as program)
    43.     private static void Main()
    44.     {
    45.         UDPSend sendObj=new UDPSend();
    46.         sendObj.init();
    47.        
    48.         // testing via console
    49.         // sendObj.inputFromConsole();
    50.        
    51.         // as server sending endless
    52.         sendObj.sendEndless(" endless infos \n");
    53.        
    54.     }
    55.     // start from unity3d
    56.     public void Start()
    57.     {
    58.         init();
    59.     }
    60.    
    61.     // OnGUI
    62.     void OnGUI()
    63.     {
    64.         Rect rectObj=new Rect(40,380,200,400);
    65.             GUIStyle style = new GUIStyle();
    66.                 style.alignment = TextAnchor.UpperLeft;
    67.         GUI.Box(rectObj,"# UDPSend-Data\n127.0.0.1 "+port+" #\n"
    68.                     + "shell> nc -lu 127.0.0.1  "+port+" \n"
    69.                 ,style);
    70.        
    71.         // ------------------------
    72.         // send it
    73.         // ------------------------
    74.         strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
    75.         if (GUI.Button(new Rect(190,420,40,20),"send"))
    76.         {
    77.             sendString(strMessage+"\n");
    78.         }      
    79.     }
    80.    
    81.     // init
    82.     public void init()
    83.     {
    84.         // Endpunkt definieren, von dem die Nachrichten gesendet werden.
    85.         print("UDPSend.init()");
    86.        
    87.         // define
    88.         IP="127.0.0.1";
    89.         port=8051;
    90.        
    91.         // ----------------------------
    92.         // Senden
    93.         // ----------------------------
    94.         remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
    95.         client = new UdpClient();
    96.        
    97.         // status
    98.         print("Sending to "+IP+" : "+port);
    99.         print("Testing: nc -lu "+IP+" : "+port);
    100.    
    101.     }
    102.  
    103.     // inputFromConsole
    104.     private void inputFromConsole()
    105.     {
    106.         try
    107.         {
    108.             string text;
    109.             do
    110.             {
    111.                 text = Console.ReadLine();
    112.  
    113.                 // Den Text zum Remote-Client senden.
    114.                 if (text != "")
    115.                 {
    116.  
    117.                     // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
    118.                     byte[] data = Encoding.UTF8.GetBytes(text);
    119.  
    120.                     // Den Text zum Remote-Client senden.
    121.                     client.Send(data, data.Length, remoteEndPoint);
    122.                 }
    123.             } while (text != "");
    124.         }
    125.         catch (Exception err)
    126.         {
    127.             print(err.ToString());
    128.         }
    129.  
    130.     }
    131.  
    132.     // sendData
    133.     private void sendString(string message)
    134.     {
    135.         try
    136.         {
    137.                 //if (message != "")
    138.                 //{
    139.  
    140.                     // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
    141.                     byte[] data = Encoding.UTF8.GetBytes(message);
    142.  
    143.                     // Den message zum Remote-Client senden.
    144.                     client.Send(data, data.Length, remoteEndPoint);
    145.                 //}
    146.         }
    147.         catch (Exception err)
    148.         {
    149.             print(err.ToString());
    150.         }
    151.     }
    152.    
    153.    
    154.     // endless test
    155.     private void sendEndless(string testStr)
    156.     {
    157.         do
    158.         {
    159.             sendString(testStr);
    160.            
    161.            
    162.         }
    163.         while(true);
    164.        
    165.     }
    166.    
    167. }
    168.  
    169.  
     
    pertsi and McGravity like this.
  2. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Thanks for sharing :)
    Have you added it to the wiki yet?
     
  3. la1n

    la1n

    Joined:
    Apr 6, 2008
    Posts:
    10
    but can do it as soon as i find the time for it .-)
     
  4. tigerspidey123

    tigerspidey123

    Joined:
    Jun 25, 2009
    Posts:
    67
    This is nice thanks.

    One thing, I think the thread and client should be disabled on OnDisable() function.

    void OnDisable()
    {
    if ( receiveThread!= null)
    receiveThread.Abort();

    client.Close();
    }

    Which next time it starts in game doesn't cause crash.
     
    Fenikkel likes this.
  5. MrRudak

    MrRudak

    Joined:
    Oct 17, 2010
    Posts:
    159
    Thanks for sharing!
     
  6. UnityStudent

    UnityStudent

    Joined:
    Dec 10, 2010
    Posts:
    3
    Thank you for sharing the codes. I have added them to the project.
    But not sure how to use them.

    Can some one help me with this?

    Many thanks!
     
  7. Adamo

    Adamo

    Joined:
    Dec 17, 2010
    Posts:
    55
    la1n:
    Thank you fpr sharing the code!

    tigerspidey123:
    Thank you for fixing the crashing problem. (Do we need to insert your addendum to both sender and receiver?)

    -Adamo
     
  8. luisanton

    luisanton

    Joined:
    Aug 25, 2009
    Posts:
    325
    Nice, thanks! Does this work with iOS basic? I'm still not sure if it supports TCP/UDP :m
     
  9. Q_B

    Q_B

    Joined:
    Nov 29, 2010
    Posts:
    14
    Very useful code indeed! Thanks for sharing!

    Among other things, this was quite useful for quickly implementing that 6dofstreamer socket streamer for FaceAPI, just for the kicks of testing it :)

    Thanks!
     
  10. MadsPB

    MadsPB

    Joined:
    Mar 26, 2010
    Posts:
    8
    When you write:
    Does this mean that you use C# to start the a new process from a script run in unity?!?:
    Code (csharp):
    1.  
    2. Process myProc = new Process();
    3. myProc.StartInfo.FileName = "c:\MyApp\startProgram";
    4. myProc.Start();
    or how is this called?
     
  11. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    right it starts a new process ("application") that runs on its own side by side to it
     
  12. rajmond

    rajmond

    Joined:
    May 18, 2010
    Posts:
    56
    What if you want to send data outside the LAN? I guess these scripts won't work?
     
  13. bmcc

    bmcc

    Joined:
    Mar 15, 2011
    Posts:
    8
    I have two questions:

    I ran your example in Unity and I get an error:

    UnityEngine.Object:ToString()
    UDPReceive:ReceiveData() (at Assets/_Common/_Scripts/_Model/UDPReceive.cs:144)

    It says something about Unity not liking when ToString is called in a thread outside of the main thread.

    Also, I need some clarification on something.

    IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
    byte[] data = client.Receive(ref anyIP);

    Looking at these two lines of code you are receiving packets from any IP address sent on any port? Or are you receiving packets from any IP address sent on the port that the client was initialized on? Shouldn't you specify the exact IP address and/or port the end point is sending packets from?

    All in all I was just wondering why most examples I see: IPEndPoint(IPAddress.Any, 0) instead of IPEndPoint(IPAddress.parse("127.0.0.1"), 8051)?

    Thanks
     
  14. leegod

    leegod

    Joined:
    May 5, 2010
    Posts:
    2,472
    I want to send UDP packet to remote server, then how to? I tried change the IP and port of default(127.0.0.1, 8051) to specific server's like (95.212.8.10, 4030), but then, this script's sending function does not work.

    Where and how must be revised for use with remote master server?
     
    Last edited: Jul 26, 2011
  15. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    is the remote server or more specifically its firewall and router configured for it? UDP packets, when they are not correctly forwarded by the hardware etc are just dropped.
     
  16. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    thats not the problem. but the server / machine you send it too must be reachable and have port forwarded.

    thats nothing that has to do with your code but the network setup.

    also if this ip is your own it might fail just by definition as not all routers are able to backroute such things
     
    _onWhere_ISit likes this.
  17. Jukkauuno

    Jukkauuno

    Joined:
    Jan 18, 2012
    Posts:
    1
    Hello,

    I'm using a modified version of this UDPClient script to receive messages from LabView. Everything works smoothly until I stop the game at Unity before ending the LabView program which is sending the UDP data. By doing this, I get the following message:

    Code (csharp):
    1. System.ObjectDisposedException: The object was used after being disposed.
    2.   at System.Net.Sockets.UdpClient.CheckDisposed () [0x00000] in <filename unknown>:0
    3.   at System.Net.Sockets.UdpClient.Receive (System.Net.IPEndPoint remoteEP) [0x00000] in <filename unknown>:0
    4.   at UDPReceiver.ReceiveUDPData () [0x0001d] in xxxxxxxxxxxxxxxxxxx\UDPReceiver.cs:95
    If I terminate LabView program before stopping the game at Unity, everything works as planned.

    I have added the following lines at the end of the code. I have tried both OnDisable and this OnApplicationQuit.

    Code (csharp):
    1.     void OnApplicationQuit () {
    2.  
    3.         if (receiveThread != null)
    4.             receiveThread.Abort();
    5.        
    6.         receiver.Close();
    7.     }
    How can I handle this situation when the server is still sending messages when I'm trying to close the connection in Unity? Usually I cannot stop the UDP sending in LabView since the messages are also used in other purposes at the same time.
     
  18. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Jukkauuno: Small tip, use the Lidgren Networking Library instead, rock solid UDP implementation that works on Mono and .NET
     
  19. goshax

    goshax

    Joined:
    Jan 16, 2012
    Posts:
    5
    Does it work in Web Player?
     
  20. falkonragno

    falkonragno

    Joined:
    May 31, 2010
    Posts:
    29
    Does anyone have this example codes working in a project to see how it is implemented? Thanks.
     
  21. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    I would recommend you to just use Lidgren (gen-3) instead, it's rock solid and really good. Using raw UDP calls like done in the scripts above is a recipe for disaster.
     
  22. Bruce_mtl

    Bruce_mtl

    Joined:
    Jul 27, 2012
    Posts:
    1
    hello! I too send data via UDP labview in order to move the 3D objects on unity but I don't see how to incorporate this code in my game ... Can you help me please?
     
  23. teramoh

    teramoh

    Joined:
    Jun 18, 2013
    Posts:
    1
    thanks sharing.

    Code (csharp):
    1. void OnApplicationQuit () {
    2.  
    3.         if (receiveThread.IsAlive) {
    4.             receiveThread.Abort();
    5.         }
    6.         receiver.Close();
    7.  }
    it is better.
    my english is poor.
    sorry
     
    preyneri likes this.
  24. CHull

    CHull

    Joined:
    Jan 20, 2014
    Posts:
    2
    Been playing about with this today and wanted to see if I could get the same message sent to two different machines. Building upon this idea for a project. I only modified the UDPSend. This is what I have:

    Code (CSharp):
    1. /*
    2.     -----------------------
    3.     UDP-Send2
    4.     -----------------------
    5.     // [url]http://msdn.microsoft.com/de-de/library/bb979228.aspx#ID0E3BAC[/url]
    6.  
    7.     // > gesendetes unter
    8.     // 127.0.0.1 : 8050 empfangen
    9.  
    10.     // nc -lu 127.0.0.1 8050
    11.         // todo: shutdown thread at the end
    12. */
    13. using UnityEngine;
    14. using System.Collections;
    15.  
    16. using System;
    17. using System.Text;
    18. using System.Net;
    19. using System.Net.Sockets;
    20. using System.Threading;
    21.  
    22. public class UDPSend2 : MonoBehaviour
    23. {
    24.     private static int localPort;
    25.    
    26.     // prefs
    27.     private string IP;  // define in init
    28.  
    29.     public int port;  // define in init
    30.  
    31.     // "connection" things
    32.     IPEndPoint remoteEndPoint;
    33.     UdpClient client;
    34.  
    35.     // ****new code****
    36.     private string IP2;
    37.     IPEndPoint remoteEndPoint2;
    38.     UdpClient client2;
    39.     // ****end new code****
    40.    
    41.     // gui
    42.     string strMessage="";
    43.    
    44.    
    45.     // call it from shell (as program)
    46.     private static void Main()
    47.     {
    48.         UDPSend2 sendObj=new UDPSend2();
    49.         sendObj.init();
    50.        
    51.         // testing via console
    52.         // sendObj.inputFromConsole();
    53.        
    54.         // as server sending endless
    55.         sendObj.sendEndless(" endless infos \n");
    56.  
    57.  
    58.  
    59.  
    60.         //****new code****
    61.         //duplicating above for another machine
    62.  
    63.         UDPSend2 sendObj2=new UDPSend2();
    64.         sendObj2.init();
    65.        
    66.         // testing via console
    67.         // sendObj.inputFromConsole();
    68.        
    69.         // as server sending endless
    70.         sendObj2.sendEndless(" endless infos \n");
    71.  
    72.         //****End new code****
    73.  
    74.  
    75.  
    76.        
    77.     }
    78.     // start from unity3d
    79.     public void Start()
    80.     {
    81.         init();
    82.     }
    83.    
    84.     // OnGUI
    85.     void OnGUI()
    86.     {
    87.         Rect rectObj=new Rect(40,380,200,400);
    88.         GUIStyle style = new GUIStyle();
    89.         style.alignment = TextAnchor.UpperLeft;
    90.         GUI.Box(rectObj,"# UDPSend-Data\n127.0.0.1 "+port+" #\n"
    91.                 + "shell> nc -lu 127.0.0.1  "+port+" \n"
    92.                 ,style);
    93.        
    94.         // ------------------------
    95.         // send it
    96.         // ------------------------
    97.         strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
    98.         if (GUI.Button(new Rect(190,420,40,20),"send"))
    99.         {
    100.             sendString(strMessage+"\n");
    101.         }    
    102.     }
    103.    
    104.     // init
    105.     public void init()
    106.     {
    107.         // Endpunkt definieren, von dem die Nachrichten gesendet werden.
    108.         // Define endpoint from which the messages are sent.
    109.         print("UDPSend.init()");
    110.        
    111.         // define
    112.         //IP="127.0.0.1"; local
    113.         IP = ""; //adam
    114.  
    115.         //****new code****
    116.         IP2 = ""; //aditya
    117.         //IP3 = ""; //conor
    118.         //****end new code****
    119.  
    120.         //port=8051;
    121.         port = 80;
    122.        
    123.         // ----------------------------
    124.         // Senden
    125.         // ----------------------------
    126.         remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
    127.         client = new UdpClient();
    128.  
    129.         //****new code****
    130.         remoteEndPoint2 = new IPEndPoint(IPAddress.Parse(IP), port);
    131.         client2 = new UdpClient();
    132.         //****end new code****
    133.        
    134.         // status
    135.         print("Sending to "+IP+" : "+port);
    136.         print("Testing: nc -lu "+IP+" : "+port);
    137.  
    138.         //****new code****
    139.         print("Sending to "+IP2+" : "+port);
    140.         print("Testing: nc -lu "+IP2+" : "+port);
    141.         //****end new code****
    142.        
    143.     }
    144.    
    145.     // inputFromConsole
    146.     private void inputFromConsole()
    147.     {
    148.         try
    149.         {
    150.             string text;
    151.             do
    152.             {
    153.                 text = Console.ReadLine();
    154.                
    155.                 // Den Text zum Remote-Client senden.
    156.                 //Send the text to the remote client
    157.                 if (text != "")
    158.                 {
    159.                    
    160.                     // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
    161.                     // Encode data with the UTF8 encoding to binary format
    162.                     byte[] data = Encoding.UTF8.GetBytes(text);
    163.                    
    164.                     // Den Text zum Remote-Client senden.
    165.                     // Send the text to the remote client
    166.                     client.Send(data, data.Length, remoteEndPoint);
    167.  
    168.                     //**** new code ****
    169.                     client2.Send(data, data.Length, remoteEndPoint2);
    170.                     //**** end new code****
    171.                 }
    172.             } while (text != "");
    173.         }
    174.         catch (Exception err)
    175.         {
    176.             print(err.ToString());
    177.         }
    178.        
    179.     }
    180.    
    181.     // sendData
    182.     private void sendString(string message)
    183.     {
    184.         try
    185.         {
    186.             //if (message != "")
    187.             //{
    188.            
    189.             // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
    190.             // Encode data with the UTF8 encoding to binary format .
    191.             byte[] data = Encoding.UTF8.GetBytes(message);
    192.            
    193.             // Den message zum Remote-Client senden.
    194.             // Send the message to the remote client .
    195.             client.Send(data, data.Length, remoteEndPoint);
    196.             //}
    197.  
    198.  
    199.             //**** new code ****
    200.             client2.Send(data, data.Length, remoteEndPoint2);
    201.             //**** end new code ****
    202.         }
    203.         catch (Exception err)
    204.         {
    205.             print(err.ToString());
    206.         }
    207.     }
    208.    
    209.    
    210.     // endless test
    211.     private void sendEndless(string testStr)
    212.     {
    213.         do
    214.         {
    215.             sendString(testStr);
    216.            
    217.            
    218.         }
    219.         while(true);
    220.        
    221.     }
    222.  
    223.  
    224.    
    225. }
    226.  
    What I get from this is that Adam (who is the first IP address) receives what I type but the owner of IP2 receives nothing. (Btw I'm not very good with code, but learning!)

    Where have I went wrong here? The idea is that both machines will receive the same message.

    Thanks
     
  25. davidlannan

    davidlannan

    Joined:
    Jul 11, 2013
    Posts:
    48
    Nothing wrong - the packet is consumed by the first receiver.
    What you are looking for is a multicast or broadcast method (so it sends to all NIC's on your network).
    After creating the UpdClient set its property EnableBroadcast to true, and it should work fine.
    You dont need two sending clients. Just one. After line 127 have something like:

    Code (CSharp):
    1. client.EnableBroadcast = true;
     
  26. FLYUPAV

    FLYUPAV

    Joined:
    Aug 1, 2013
    Posts:
    34
    Hi

    Sorry I am not a talent coder, I want to use a simple string which is sent by UDPSend, then trigger an event,but I can't figure out how to tell my game object whether the string is received or not?
     
  27. ekypri07

    ekypri07

    Joined:
    May 22, 2015
    Posts:
    1
    It's work but I have crashing problem
     
  28. RealSoftGames

    RealSoftGames

    Joined:
    Jun 8, 2014
    Posts:
    220
    if possible can you please explain how you are able to run an application with Main method along side unitity?

    and when you run receive fro ma separate thread and pass messages through to unity it says that i am unable to do it because its not from the main thread, how can we combat this?
     
  29. diegoguz1990

    diegoguz1990

    Joined:
    Mar 29, 2016
    Posts:
    1
    Hello, someone can tell me ¿how test the code? thank you very much!
     
  30. MecArcher

    MecArcher

    Joined:
    Feb 10, 2017
    Posts:
    1
    Does it work in android?
     
  31. lllllllllllllllllllllll7

    lllllllllllllllllllllll7

    Joined:
    Dec 6, 2016
    Posts:
    1
    At me this code did not work corretly and freeze editor.
    I made my asynchronous version.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Net.Sockets;
    3. using System.Net;
    4. using System.Text;
    5. using System;
    6.  
    7. public class UDPRT : ScriptableObject
    8. {
    9.     static public string ReceivedMsg;                                      // INPUT DATA
    10.     static private UdpClient udpc;
    11.     static  IPEndPoint IP;
    12.     static private object obj;
    13.     static private AsyncCallback AC;
    14.     static byte[] DATA;
    15.    
    16.     public static UDPRT CreateInstance(int Port)                          // RECEVE UDP
    17.     {
    18.             IP = new IPEndPoint(IPAddress.Any, Port);
    19.             udpc = new UdpClient(Port);
    20.             AC = new AsyncCallback(ReceiveIt);
    21.             StartUdpReceive();
    22.            return ScriptableObject.CreateInstance<UDPRT>();
    23.     }
    24.  
    25.     public static UDPRT CreateInstance(int Port, string Host,string msg)  // SEND UDP
    26.     {
    27.         udpc = new UdpClient(Host,Port);
    28.         AC = new AsyncCallback(SendIt);
    29.         byte[] data = Encoding.UTF8.GetBytes(msg);
    30.         udpc.BeginSend(data, data.Length, AC, obj);
    31.         return ScriptableObject.CreateInstance<UDPRT>();
    32.     }
    33.  
    34.     static void ReceiveIt(IAsyncResult result)
    35.     {
    36.         DATA = (udpc.EndReceive(result, ref IP));
    37.         Debug.Log(Encoding.UTF8.GetString(DATA));
    38.         ReceivedMsg = Encoding.UTF8.GetString(DATA);
    39.         StartUdpReceive();
    40.     }
    41.  
    42.     static void SendIt(IAsyncResult result)
    43.     {
    44.         udpc.EndSend(result);
    45.     }
    46.  
    47.  
    48.     static void StartUdpReceive()
    49.     {
    50.         udpc.BeginReceive(AC, obj);
    51.     }
    52. }
    53.  
     
    fxcarl and NovaDynamics like this.
  32. waqas_haxhmi

    waqas_haxhmi

    Joined:
    Jun 15, 2016
    Posts:
    15
    I have running this code in unity as well as on build . I want to share message to all builds. Is it possible
     
  33. div123

    div123

    Joined:
    Jul 18, 2013
    Posts:
    2
    I have tested UDPReceive and UDPSend on machine which works fine
    but when i transfer UDPSend script on android device and UDPReceive on windows machine
    so from android device i am not able to send data
    what may cause this can any one point out
     
  34. MattijsKneppers

    MattijsKneppers

    Joined:
    Jun 30, 2014
    Posts:
    15
    Hi all, thanks for the examples. I wrapped this into an async UdpConnection class (below) that I found intuitive to use, perhaps it is of use to someone here too.

    Usage:

    Code (CSharp):
    1.     private UdpConnection connection;
    2.  
    3.     void Start()
    4.     {
    5.         string sendIp = "127.0.0.1";
    6.         int sendPort = 8881;
    7.         int receivePort = 11000;
    8.  
    9.         connection = new UdpConnection();
    10.         connection.StartConnection(sendIp, sendPort, receivePort);
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.         foreach (var message in connection.getMessages()) Debug.Log(message);
    16.  
    17.         connection.Send("Hi!");
    18.     }
    19.  
    20.     void OnDestroy()
    21.     {
    22.         connection.Stop();
    23.     }
    24.  
    UdpConnection.cs:

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Net;
    4. using System.Net.Sockets;
    5. using System.Text;
    6. using System.Threading;
    7. using UnityEngine;
    8.  
    9. public class UdpConnection
    10. {
    11.     private UdpClient udpClient;
    12.  
    13.     private readonly Queue<string> incomingQueue = new Queue<string>();
    14.     Thread receiveThread;
    15.     private bool threadRunning = false;
    16.     private string senderIp;
    17.     private int senderPort;
    18.  
    19.     public void StartConnection(string sendIp, int sendPort, int receivePort)
    20.     {
    21.         try { udpClient = new UdpClient(receivePort); }
    22.         catch (Exception e)
    23.         {
    24.             Debug.Log("Failed to listen for UDP at port " + receivePort + ": " + e.Message);
    25.             return;
    26.         }
    27.         Debug.Log("Created receiving client at ip  and port " + receivePort);
    28.         this.senderIp = sendIp;
    29.         this.senderPort = sendPort;
    30.  
    31.         Debug.Log("Set sendee at ip " + sendIp + " and port " + sendPort);
    32.  
    33.         StartReceiveThread();
    34.     }
    35.  
    36.     private void StartReceiveThread()
    37.     {
    38.         receiveThread = new Thread(() => ListenForMessages(udpClient));
    39.         receiveThread.IsBackground = true;
    40.         threadRunning = true;
    41.         receiveThread.Start();
    42.     }
    43.  
    44.     private void ListenForMessages(UdpClient client)
    45.     {
    46.         IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    47.  
    48.         while (threadRunning)
    49.         {
    50.             try
    51.             {
    52.                 Byte[] receiveBytes = client.Receive(ref remoteIpEndPoint); // Blocks until a message returns on this socket from a remote host.
    53.                 string returnData = Encoding.UTF8.GetString(receiveBytes);
    54.  
    55.                 lock (incomingQueue)
    56.                 {
    57.                     incomingQueue.Enqueue(returnData);
    58.                 }
    59.             }
    60.             catch (SocketException e)
    61.             {
    62.                 // 10004 thrown when socket is closed
    63.                 if (e.ErrorCode != 10004) Debug.Log("Socket exception while receiving data from udp client: " + e.Message);
    64.             }
    65.             catch (Exception e)
    66.             {
    67.                 Debug.Log("Error receiving data from udp client: " + e.Message);
    68.             }
    69.             Thread.Sleep(1);
    70.         }
    71.     }
    72.  
    73.     public string[] getMessages()
    74.     {
    75.         string[] pendingMessages = new string[0];
    76.         lock (incomingQueue)
    77.         {
    78.             pendingMessages = new string[incomingQueue.Count];
    79.             int i = 0;
    80.             while (incomingQueue.Count != 0)
    81.             {
    82.                 pendingMessages[i] = incomingQueue.Dequeue();
    83.                 i++;
    84.             }
    85.         }
    86.  
    87.         return pendingMessages;
    88.     }
    89.  
    90.     public void Send(string message)
    91.     {
    92.         Debug.Log(String.Format("Send msg to ip:{0} port:{1} msg:{2}",senderIp,senderPort,message));
    93.         IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse(senderIp), senderPort);
    94.         Byte[] sendBytes = Encoding.UTF8.GetBytes(message);
    95.         udpClient.Send(sendBytes, sendBytes.Length, serverEndpoint);
    96.     }
    97.  
    98.     public void Stop()
    99.     {
    100.         threadRunning = false;
    101.         receiveThread.Abort();
    102.         udpClient.Close();
    103.     }
    104. }
    105.  
     
  35. ganyotcu

    ganyotcu

    Joined:
    Jan 25, 2017
    Posts:
    1
    thank you so much for sharing,
    and codes are working for android too, I tried.
    if anyone have problem with editor freezing can read teramoh comment.

     
  36. albondgames

    albondgames

    Joined:
    Jul 19, 2018
    Posts:
    8
    You are a lifesaver! Thanks so much for the code.
     
  37. ChayanneHola

    ChayanneHola

    Joined:
    Dec 6, 2019
    Posts:
    1
    EXCELENTE!!!
    Muchas gracias amigo por compartir tu código!!:):)
    Me ha sido de muchísima ayuda !!
     
  38. addavies

    addavies

    Joined:
    May 18, 2018
    Posts:
    8
    Thank you so much!
     
  39. kurtalp

    kurtalp

    Joined:
    Mar 21, 2015
    Posts:
    4
    Thanks for sharing
     
  40. adammpolak

    adammpolak

    Joined:
    Sep 9, 2018
    Posts:
    450
    You are the hero we need, but not the one we deserve
     
    Fenikkel and seejayjames like this.
  41. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    687
    Here's a stripped-down version (based on the above posts) for sending strings or integer lists over UDP. It has two sample strings and an int list which you can send using keystrokes for testing. IP and port are hard-coded, no error checking. Seems to work just fine.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Text;
    3. using System.Net;
    4. using System.Net.Sockets;
    5.  
    6. public class udpScriptSimple : MonoBehaviour
    7. {
    8.  
    9.     // Simple version of UDP sending script
    10.     // Hardcode IP and port of receiver, no error checking on send
    11.     // Sample string and number list messages you can send with keystrokes, for testing
    12.  
    13.     IPEndPoint remoteEndPoint;
    14.     UdpClient client;
    15.  
    16.     string strMessage1 = "hello world";
    17.     string strMessage2 = "how are you";
    18.     int[] numberMessage = { 0, 10, 50, 100, 150, 200, 250, 255 };
    19.  
    20.     void Start()
    21.     {
    22.         // IP and port
    23.         remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
    24.         client = new UdpClient();
    25.     }
    26.  
    27.     void Update()
    28.     {
    29.  
    30.         if (Input.GetKeyDown(KeyCode.U)) // U for "UDP", single message
    31.         {
    32.             sendString(strMessage1);
    33.         }
    34.         if (Input.GetKey(KeyCode.C)) // C for "Continuous" messages, one per frame while key held down
    35.         {
    36.             sendString(strMessage2);
    37.         }
    38.         if (Input.GetKey(KeyCode.N)) // N for "Number" messages, one per frame while key held down
    39.         {
    40.             sendNumberList(numberMessage);
    41.         }
    42.     }
    43.  
    44.     // Method to send string messages
    45.     public void sendString(string message)
    46.     {
    47.         byte[] stringList = Encoding.UTF8.GetBytes(message);
    48.         client.Send(stringList, stringList.Length, remoteEndPoint);
    49.         print("message " + message + " sent to " + remoteEndPoint);
    50.     }
    51.  
    52.     // Method to send an int[] array, like texture RGB values, etc
    53.     public void sendNumberList(int[] message)
    54.     {
    55.         byte[] intList = new byte[message.Length];
    56.  
    57.         // There may be a way to convert the whole int array at once instead of looping through it
    58.         // Tried Buffer.blockCopy, but haven't gotten it to work yet
    59.         // https://forum.unity.com/threads/convert-int-array-to-byte-array-all-at-once.1077113/#post-6947678
    60.         for (int i = 0; i < message.Length; i++)
    61.         {
    62.             intList[i] = ((byte)message[i]);
    63.         }
    64.  
    65.         client.Send(intList, intList.Length, remoteEndPoint);
    66.         print("message " + message + " sent to " + remoteEndPoint);
    67.     }
    68. }
    69.  
     
    ROBYER1 and Fenikkel like this.
  42. fatalerror233

    fatalerror233

    Joined:
    Mar 12, 2021
    Posts:
    1
    Thanks a lot!
     
  43. sungsoos-mess

    sungsoos-mess

    Joined:
    Feb 22, 2021
    Posts:
    2
    Thanks MattijsKneppers. This saved me a whole lot of work. A very nice and simple package.

     
  44. adammpolak

    adammpolak

    Joined:
    Sep 9, 2018
    Posts:
    450
    unity_dev421 and Boyozu like this.