Search Unity

Unity and UDP

Discussion in 'Unity Distribution Portal (UDP)' started by charanchaganti, May 10, 2022.

  1. charanchaganti

    charanchaganti

    Joined:
    Mar 16, 2022
    Posts:
    13
    We need to communicate between two exes' in two different systems using UDPClient. Both the systems are connected on ethernet.

    Please help how to organize server and client combing both unity and UDPClient. Have tried many tutorials and scripts available online. Nothing seems to work out. Please help me and share the code if you have any
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,428
    what is the issue/error in those tests? Cannot connect or something else?

    i've had success with those scripts from google searches like: unity udp async
    or just regular: c# simple udp async
     
    Antypodish likes this.
  3. charanchaganti

    charanchaganti

    Joined:
    Mar 16, 2022
    Posts:
    13
    I could receive the message (receiver code is given below) in unity using UDP from other source but I am unable to send any messages from my form I created in unity

    public class TestingUDP : MonoBehaviour
    {
    // Start is called before the first frame update
    UdpClient client;
    Thread UdpThread;
    IPEndPoint anyIP;
    public string text;

    void Start()
    {
    client = new UdpClient(12345);
    anyIP = new IPEndPoint(IPAddress.Any, 0);
    UdpThread = new Thread(new ThreadStart(ThreadMethod));
    UdpThread.Start();

    }
    // Update is called once per frame
    void Update()
    {
    }
    private void ThreadMethod()
    {
    while (true)
    {
    try
    {
    byte[] data = client.Receive(ref anyIP);
    //Debug.Log(anyIP);
    string textdata = Encoding.UTF8.GetString(data);
    //string[] textarray = textdata.Split('#');
    //text = textarray[5];
    text = textdata;
    Debug.Log(text);
    }
    catch { }
    }
    }
    private void OnApplicationQuit()
    {
    UdpThread.Abort();
    }
     
  4. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,428
  5. charanchaganti

    charanchaganti

    Joined:
    Mar 16, 2022
    Posts:
    13
    Code (CSharp):
    1. using System.Net;
    2. using System.Net.Sockets;
    3. using System.Text;
    4. using System.Threading;
    5. using UnityEngine;
    6. using UnityEngine.UI;
    7. using UnityEngine.Networking;
    8.  
    9. public class UDPManager : MonoBehaviour
    10. {
    11.  
    12.     // Start is called before the first frame update
    13.     UdpClient client;
    14.     Thread UdpThread;
    15.     IPEndPoint currentIP;
    16.     public string testMessage = "test";
    17.     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    18.     IPAddress address;
    19.     int port = 12345;
    20.    
    21.     void Start()
    22.     {
    23.  
    24.         address = IPAddress.Parse("192.168.1.9");
    25.         currentIP = new IPEndPoint(address, port);
    26.         UdpThread = new Thread(new ThreadStart(ThreadMethod));
    27.         UdpThread.Start();
    28.  
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.  
    35.     }
    36.     private void ThreadMethod()
    37.     {
    38.         while (true)
    39.         {
    40.            
    41.             s.Bind(currentIP);
    42.             byte[] data = Encoding.UTF8.GetBytes(testMessage);
    43.             IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0);
    44.             s.SendTo(data, data.Length, SocketFlags.None, ep);
    45.             Debug.Log(testMessage);          
    46.         }
    47.     }
    48.     private void OnApplicationQuit()
    49.     {
    50.         UdpThread.Abort();
    51.         s.Close();
    52.     }
    53. }
    54.  
     
  6. charanchaganti

    charanchaganti

    Joined:
    Mar 16, 2022
    Posts:
    13
    This is the script I attached for sending messages

    SocketException: The requested address is not valid in its context.
    This is the error I am getting
     
  7. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,980
    You should try actually connecting to the host, and seeing if you get any errors. The way you are using UDPClient is really weird.

    I suggest reading up on how to use UDPClient and looking at examples of usage on something like msdn https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.udpclient?view=net-6.0
     
  8. charanchaganti

    charanchaganti

    Joined:
    Mar 16, 2022
    Posts:
    13
    Thanks for the response
    Please let me know where exactly I am doing mistake

    We don't have a host here, systems are not connected to internet. Both the systems are connected with a LAN cable and one acts as server and the other as client
     
  9. lmbarns

    lmbarns

    Joined:
    Jul 14, 2011
    Posts:
    1,628
    They're both on the same local network yes? Both machines need a local ip address and need to be on the same local network.

    Both computers have to have a port open to receive a message, usually you'd have a listening port and send on a different one.

    Code (CSharp):
    1. using System;
    2. using System.Net;
    3. using System.Net.Sockets;
    4. using System.Text;
    5. using UnityEngine;
    6.  
    7. using System.Threading;
    8. public class UDPListener : MonoBehaviour
    9. {
    10.     private const int listenPort = 11000;
    11.     UdpClient listener = new UdpClient(listenPort);
    12.     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
    13.     void Start()
    14.     {
    15.         Thread thread = new Thread(Receive);
    16.         thread.Start();
    17.     }
    18.  
    19.     private void Receive()
    20.     {
    21.         try
    22.         {
    23.             while (true)
    24.             {
    25.                 print("Waiting for broadcast");
    26.                 byte[] bytes = listener.Receive(ref groupEP);
    27.  
    28.                 print($"Received broadcast from {groupEP} :");
    29.                 print($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
    30.  
    31.             }
    32.         }
    33.         catch (SocketException e)
    34.         {
    35.             print(e);
    36.         }
    37.     }
    38.     private void OnDestroy()
    39.     {
    40.         listener.Close();
    41.     }
    42. }
    And to test

    Code (CSharp):
    1. using System.Net.Sockets;
    2. using System.Net;
    3. using System;
    4. using System.Text;
    5.  
    6. public class UDPClient : MonoBehaviour
    7. {
    8.     IEnumerator Start()
    9.     {
    10.         yield return new WaitForSeconds(1);
    11.         Send("test test test");
    12.     }
    13.     private void Send(string msg)
    14.     {
    15.         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    16.  
    17.         IPAddress targetAddress = IPAddress.Parse("127.0.0.1");
    18.  
    19.         byte[] sendbuf = Encoding.ASCII.GetBytes(msg);
    20.         IPEndPoint ep = new IPEndPoint(targetAddress, 11000);
    21.  
    22.         s.SendTo(sendbuf, ep); s.Close();
    23.  
    24.         print("Message sent");
    25.     }
    26. }
    27.  
    28.  
    Works on the same machine if you drag both scripts onto an object and press play. Change the ip to your target machine's local ip address
     
    Last edited: May 16, 2022
    ROBYER1 and UCF50 like this.
  10. RiverExplorer

    RiverExplorer

    Joined:
    Jul 28, 2021
    Posts:
    21
    You code does not run.[

    UdpClient listener = new UdpClient(listenPort);
    --> IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

    On the new IPEndPoint(..) line, I get:
    System.Net.Socket.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted at System.Net.Sockets.Socket.Bind(System.Net.EndPoint localEP).
     
  11. denizyunusgogus

    denizyunusgogus

    Joined:
    Aug 7, 2020
    Posts:
    1
    A bit late reply but if you move "listener = new UdpClient(listenPort);" to Start function, then it works well. @lmbarns thank you for the code, saved my day, was stuck in threads instead of ol' good enumerators :')