Search Unity

UDP Interaction

Discussion in 'Package Manager' started by unity_4J-FEv3jCWkBSQ, Jan 29, 2020.

  1. unity_4J-FEv3jCWkBSQ

    unity_4J-FEv3jCWkBSQ

    Joined:
    Jan 6, 2020
    Posts:
    9
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Text;
    5. using System.Net;
    6. using System.Net.Sockets;
    7. using System.Threading;
    8. public class UDPSend : MonoBehaviour
    9. {
    10.     private static int localPort;
    11.  
    12.     // prefs
    13.     private string IP;  // define in init
    14.     public int port;  // define in init
    15.  
    16.     // "connection" things
    17.     IPEndPoint remoteEndPoint;
    18.     UdpClient client;
    19.  
    20.     // gui
    21.     string strMessage="";
    22.  
    23.      
    24.     // call it from shell (as program)
    25.     private static void Main()
    26.     {
    27.         UDPSend sendObj=new UDPSend();
    28.         sendObj.init();
    29.      
    30.         // testing via console
    31.         // sendObj.inputFromConsole();
    32.      
    33.         // as server sending endless
    34.         sendObj.sendEndless(" endless infos \n");
    35.      
    36.     }
    37.     // start from unity3d
    38.     public void Start()
    39.     {
    40.         init();
    41.     }
    42.  
    43.     // OnGUI
    44.     void OnGUI()
    45.     {
    46.         Rect rectObj=new Rect(40,380,200,400);
    47.             GUIStyle style = new GUIStyle();
    48.                 style.alignment = TextAnchor.UpperLeft;
    49.         GUI.Box(rectObj,"# UDPSend-Data\n127.0.0.1 "+port+" #\n"
    50.                     + "shell> nc -lu 127.0.0.1  "+port+" \n"
    51.                 ,style);
    52.      
    53.         // ------------------------
    54.         // send it
    55.         // ------------------------
    56.         strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
    57.         if (GUI.Button(new Rect(190,420,40,20),"send"))
    58.         {
    59.             sendString(strMessage+"\n");
    60.         }    
    61.     }
    62.  
    63.     // init
    64.     public void init()
    65.     {
    66.         // Endpunkt definieren, von dem die Nachrichten gesendet werden.
    67.         print("UDPSend.init()");
    68.      
    69.         // define
    70.         IP="127.0.0.1";
    71.         port=8051;
    72.      
    73.         // ----------------------------
    74.         // Senden
    75.         // ----------------------------
    76.         remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
    77.         client = new UdpClient();
    78.      
    79.         // status
    80.         print("Sending to "+IP+" : "+port);
    81.         print("Testing: nc -lu "+IP+" : "+port);
    82.  
    83.     }
    84.     // inputFromConsole
    85.     private void inputFromConsole()
    86.     {
    87.         try
    88.         {
    89.             string text;
    90.             do
    91.             {
    92.                 text = Console.ReadLine();
    93.                 // Den Text zum Remote-Client senden.
    94.                 if (text != "")
    95.                 {
    96.                     // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
    97.                     byte[] data = Encoding.UTF8.GetBytes(text);
    98.                     // Den Text zum Remote-Client senden.
    99.                     client.Send(data, data.Length, remoteEndPoint);
    100.                 }
    101.             } while (text != "");
    102.         }
    103.         catch (Exception err)
    104.         {
    105.             print(err.ToString());
    106.         }
    107.     }
    108.     // sendData
    109.     private void sendString(string message)
    110.     {
    111.         try
    112.         {
    113.                 //if (message != "")
    114.                 //{
    115.                     // Daten mit der UTF8-Kodierung in das Binärformat kodieren.
    116.                     byte[] data = Encoding.UTF8.GetBytes(message);
    117.                     // Den message zum Remote-Client senden.
    118.                     client.Send(data, data.Length, remoteEndPoint);
    119.                 //}
    120.         }
    121.         catch (Exception err)
    122.         {
    123.             print(err.ToString());
    124.         }
    125.     }
    126.  
    127.  
    128.     // endless test
    129.     private void sendEndless(string testStr)
    130.     {
    131.         do
    132.         {
    133.             sendString(testStr);
    134.          
    135.          
    136.         }
    137.         while(true);
    138.      
    139.     }
    140.  
    141. }
    142.  
    143.  
    144.  
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Text;
    5. using System.Net;
    6. using System.Net.Sockets;
    7. using System.Threading;
    8. public class UDPReceive : MonoBehaviour {
    9.  
    10.     // receiving Thread
    11.     Thread receiveThread;
    12.     // udpclient object
    13.     UdpClient client;
    14.     // public
    15.     // public string IP = "127.0.0.1"; default local
    16.     public int port; // define > init
    17.     // infos
    18.     public string lastReceivedUDPPacket="";
    19.     public string allReceivedUDPPackets=""; // clean up this from time to time!
    20.  
    21.  
    22.     // start from shell
    23.     private static void Main()
    24.     {
    25.        UDPReceive receiveObj=new UDPReceive();
    26.        receiveObj.init();
    27.         string text="";
    28.         do
    29.         {
    30.              text = Console.ReadLine();
    31.         }
    32.         while(!text.Equals("exit"));
    33.     }
    34.     // start from unity3d
    35.     public void Start()
    36.     {
    37.      
    38.         init();
    39.     }
    40.  
    41.     // OnGUI
    42.     void OnGUI()
    43.     {
    44.         Rect rectObj=new Rect(40,10,200,400);
    45.             GUIStyle style = new GUIStyle();
    46.                 style.alignment = TextAnchor.UpperLeft;
    47.         GUI.Box(rectObj,"# UDPReceive\n106.51.8.242 "+port+" #\n"
    48.                     + "shell> nc -u 106.51.8.242 : "+port+" \n"
    49.                     + "\nLast Packet: \n"+ lastReceivedUDPPacket
    50.                     + "\n\nAll Messages: \n"+allReceivedUDPPackets
    51.                 ,style);
    52.     }
    53.      
    54.     // init
    55.     private void init()
    56.     {
    57.         // Endpunkt definieren, von dem die Nachrichten gesendet werden.
    58.         print("UDPSend.init()");
    59.      
    60.         // define port
    61.         port = 443;
    62.         // status
    63.         print("Sending to 127.0.0.1 : "+port);
    64.         print("Test-Sending to this Port: nc -u 127.0.0.1  "+port+"");
    65.  
    66.         // ----------------------------
    67.         // Abhören
    68.         // ----------------------------
    69.         // Lokalen Endpunkt definieren (wo Nachrichten empfangen werden).
    70.         // Einen neuen Thread für den Empfang eingehender Nachrichten erstellen.
    71.         receiveThread = new Thread(
    72.             new ThreadStart(ReceiveData));
    73.         receiveThread.IsBackground = true;
    74.         receiveThread.Start();
    75.     }
    76.     // receive thread
    77.     private  void ReceiveData()
    78.     {
    79.         client = new UdpClient(port);
    80.         while (true)
    81.         {
    82.             try
    83.             {
    84.                 // Bytes empfangen.
    85.                 IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
    86.                 byte[] data = client.Receive(ref anyIP);
    87.                 // Bytes mit der UTF8-Kodierung in das Textformat kodieren.
    88.                 string text = Encoding.UTF8.GetString(data);
    89.                 // Den abgerufenen Text anzeigen.
    90.                 print(">> " + text);
    91.              
    92.                 // latest UDPpacket
    93.                 lastReceivedUDPPacket=text;
    94.              
    95.                 // ....
    96.                 allReceivedUDPPackets=allReceivedUDPPackets+text;
    97.              
    98.             }
    99.             catch (Exception err)
    100.             {
    101.                 print(err.ToString());
    102.             }
    103.         }
    104.     }
    105.  
    106.     // getLatestUDPPacket
    107.     // cleans up the rest
    108.     public string getLatestUDPPacket()
    109.     {
    110.         allReceivedUDPPackets="";
    111.         return lastReceivedUDPPacket;
    112.     }
    113. }
    I am trying to send co-ordinates as string from one system to other, read the string in the next system and move a object accordingly. I am using UDP for the transmission purpose. I got the code to send and recieve string using UDP from the forum itself but it uses a dummy IP and port to connect which only works if both the programs i.e send and recieve are on the same system which does not suffice my requirement. I tried changing the IP to the IP of the other system but i can't figure what should i change the port to.
    Can someone tell how to know the port of any server or what should i change?
     
    Last edited: Jan 29, 2020
  2. okcompute_unity

    okcompute_unity

    Unity Technologies

    Joined:
    Jan 16, 2017
    Posts:
    756