1. We're looking for feedback on Unity Starter Kits! Let us know what you’d like.
    Dismiss Notice
  2. Unity 2017.2 beta is now available for download.
    Dismiss Notice
  3. Unity 2017.1 is now released.
    Dismiss Notice
  4. Introducing the Unity Essentials Packs! Find out more.
    Dismiss Notice
  5. Check out all the fixes for 5.6 on the patch releases page.
    Dismiss Notice
  6. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice

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

Discussion in 'Multiplayer Networking' 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.  
     
  2. AngryAnt

    AngryAnt

    Keyboard Operator Moderator

    Joined:
    Oct 25, 2005
    Posts:
    3,037
    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.
     
  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:
    316
    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,596
    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:
    1,632
    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,596
    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,596
    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
     
  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:
    1,782
    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:
    1,782
    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.  
    2.         if (receiveThread.IsAlive) {
    3.             receiveThread.Abort();
    4.         }
    5.         receiver.Close();
    6.  }
    it is better.
    my english is poor.
    sorry
     
  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:
    36
    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. ymassuot

    ymassuot

    Joined:
    Aug 1, 2013
    Posts:
    27
    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. aquilinajake

    aquilinajake

    Joined:
    Jun 8, 2014
    Posts:
    204
    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.  
     
  32. waqas_haxhmi

    waqas_haxhmi

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