Search Unity

Question Receiving UDP packets

Discussion in 'Multiplayer' started by p4rk3r0vsky, Nov 3, 2020.

  1. p4rk3r0vsky

    p4rk3r0vsky

    Joined:
    Nov 3, 2020
    Posts:
    6
    I wrote code to get UDP packets which contains info from my phone's accelerometer + gyroscope and it works as console app in Visual Studio but not in Unity. How to make it work in Unity?

    PS I am newbie to c# & unity.

    Console Code:

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4.  
    5. using System.Net;
    6. using System.Net.Sockets;
    7.  
    8. using System.Threading;
    9. namespace ConsoleApp1
    10. {
    11.     class Program
    12.     {
    13.         static void Main(string[] args)
    14.         {
    15.             //Creates a UdpClient for reading incoming data.
    16.             UdpClient receivingUdpClient = new UdpClient(5555);
    17.  
    18.             //Creates an IPEndPoint to record the IP Address and port number of the sender.
    19.             // The IPEndPoint will allow you to read datagrams sent from any source.
    20.             IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    21.             while (true) {
    22.             try
    23.             {
    24.  
    25.                 // Blocks until a message returns on this socket from a remote host.
    26.                 Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
    27.  
    28.                 string returnData = Encoding.ASCII.GetString(receiveBytes);
    29.  
    30.                 Console.WriteLine("This is the message you received " +
    31.                                           returnData.ToString());
    32.                 Console.WriteLine("This message was sent from " +
    33.                                             RemoteIpEndPoint.Address.ToString() +
    34.                                             " on their port number " +
    35.                                             RemoteIpEndPoint.Port.ToString());
    36.                 Thread.Sleep(500);
    37.             }
    38.             catch (Exception e)
    39.             {
    40.                 Console.WriteLine(e.ToString());
    41.             }
    42.  
    43.             }
    44.  
    45.         }
    46.     }
    47. }
    48.  


    My Unity implementation:
    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4.  
    5. using System.Net;
    6. using System.Net.Sockets;
    7.  
    8. using System.Threading;
    9. //using System.Collections;
    10. //using System.Collections.Generic;
    11. using UnityEngine;
    12.  
    13. public class UDP : MonoBehaviour
    14. {
    15.     //Creates a UdpClient for reading incoming data.
    16.     UdpClient receivingUdpClient = new UdpClient(5555);
    17.  
    18.     //Creates an IPEndPoint to record the IP Address and port number of the sender.
    19.     // The IPEndPoint will allow you to read datagrams sent from any source.
    20.     IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    21.  
    22.     void Start()
    23.     {
    24.  
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void FixedUpdate()
    29.     {
    30.  
    31.  
    32.    
    33.             try
    34.             {
    35.  
    36.                 // Blocks until a message returns on this socket from a remote host.
    37.                 Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
    38.  
    39.                 string returnData = Encoding.ASCII.GetString(receiveBytes);
    40.  
    41.                 Debug.Log("This is the message you received " +
    42.                                           returnData.ToString());
    43.                 Debug.Log("This message was sent from " +
    44.                                             RemoteIpEndPoint.Address.ToString() +
    45.                                             " on their port number " +
    46.                                             RemoteIpEndPoint.Port.ToString());
    47.  
    48.             }
    49.             catch (Exception e)
    50.             {
    51.                 Debug.Log(e.ToString());
    52.             }
    53.  
    54.    
    55.  
    56.     }
    57. }
    58.  


    ERROR MESSAGE:
    System.NullReferenceException: Object reference not set to an instance of an object
    at UDP.FixedUpdate () [0x00002] in C:\...\Scripts\UDP.cs:37
    UnityEngine.Debug:Log(Object)
    UDP:FixedUpdate() (at Assets/Scripts/UDP.cs:51)
     
    Last edited: Nov 4, 2020
  2. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,072
  3. FakeByte

    FakeByte

    Joined:
    Dec 8, 2015
    Posts:
    147
    Initialize your variables in the start method

    //Creates a UdpClient for reading incoming data.
    UdpClient receivingUdpClient;

    //Creates an IPEndPoint to record the IP Address and port number of the sender.
    // The IPEndPoint will allow you to read datagrams sent from any source.
    IPEndPoint RemoteIpEndPoint;

    void Start()
    {
    receivingUdpClient = new UdpClient(5555);
    RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
    }
     
  4. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,445
  5. p4rk3r0vsky

    p4rk3r0vsky

    Joined:
    Nov 3, 2020
    Posts:
    6
    I read all of that and tried fix it. Now it doesn't show error but doesn't show message aswell. I didn't initialize in start() 'cause it gave me error.

    unity script code:

    Code (CSharp):
    1. using System;
    2. using System.Text;
    3. using System.Net;
    4. using System.Net.Sockets;
    5. using UnityEngine;
    6.  
    7. public class UDP : MonoBehaviour
    8. {
    9.  
    10.     void FixedUpdate()
    11.     {
    12.         PUdp.Create();
    13.         PUdp.BeginReceive();
    14.     }
    15. }
    16.  
    17. internal static class PUdp
    18. {
    19.     private static UdpClient socket;
    20.     public static void Create()
    21.     {
    22.         if (socket == null)
    23.             socket = new UdpClient(5555);
    24.     }
    25.     public static void BeginReceive()
    26.     {
    27.         socket.BeginReceive(new AsyncCallback(OnUdpData), socket);
    28.     }
    29.  
    30.     private static void OnUdpData(IAsyncResult result)
    31.     {
    32.         UdpClient socket = result.AsyncState as UdpClient;
    33.         IPEndPoint source = new IPEndPoint(0, 0);
    34.         byte[] message = socket.EndReceive(result, ref source);
    35.         string returnData = Encoding.ASCII.GetString(message);
    36.         Debug.Log("Data: " + returnData.ToString() + " from " + source);
    37.     }
    38. }




    as just normal 'console app' in visual studio it still works well
    Code (csharp):
    1.  
    2. using System;
    3. using System.Text;
    4. using System.Net;
    5. using System.Net.Sockets;
    6.  
    7. namespace UdpTest
    8. {
    9.     class Program
    10.     {
    11.  
    12.         static void Main(string[] args)
    13.         {
    14.             PUdp.Create();
    15.             PUdp.BeginReceive();
    16.             Console.ReadKey();
    17.         }
    18.  
    19.  
    20.         internal static class PUdp
    21.         {
    22.             private static UdpClient socket;
    23.             public static void Create()
    24.             {
    25.                 if (socket == null)
    26.                     socket = new UdpClient(5555);
    27.             }
    28.             public static void BeginReceive()
    29.             {
    30.                 socket.BeginReceive(new AsyncCallback(OnUdpData), socket);
    31.             }
    32.  
    33.             private static void OnUdpData(IAsyncResult result)
    34.             {
    35.                 UdpClient socket = result.AsyncState as UdpClient;
    36.                 IPEndPoint source = new IPEndPoint(0, 0);
    37.                 byte[] message = socket.EndReceive(result, ref source);
    38.                 string returnData = Encoding.ASCII.GetString(message);
    39.                 Console.WriteLine("Data: " + returnData.ToString() + " from " + source);
    40.                          
    41.             }
    42.         }
    43.     }
    44. }
     
  6. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Doing 50 BeginReceive calls a second doesn't seem right to me. In my own code I do this on a separate thread, and first check socket.Available. Only if true do I try to get the data. FixedUpdate is only for physics related code by the way.

    But if you aren't actually receiving data, you should not expect to see any messages in the console with the code you are using. EndReceive just blocks until it receives any data, and you have no debugging ahead of it. After a short time you probably have thousands of instances of EndReceive just waiting to receive data to eternity. So add more debugging at minimum. For all I know you might just have your software firewall set to block access to Unity so you're not receiving anything.
     
  7. p4rk3r0vsky

    p4rk3r0vsky

    Joined:
    Nov 3, 2020
    Posts:
    6
    Code (CSharp):
    1. using System;
    2. using System.Text;
    3. using System.Net;
    4. using System.Net.Sockets;
    5. using UnityEngine;
    6.  
    7. public class UDP : MonoBehaviour
    8. {
    9.  
    10.     void Start()
    11.     {
    12.         PUdp.Create();
    13.         Debug.Log("Start");
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         if (Input.GetKeyDown("f"))
    19.         {
    20.             PUdp.BeginReceive();
    21.             Debug.Log("Update");
    22.         }
    23.     }
    24. }
    25.  
    26. internal static class PUdp
    27. {
    28.     private static UdpClient socket;
    29.     public static void Create()
    30.     {
    31.         if (socket == null)
    32.             socket = new UdpClient(5555);
    33.     }
    34.     public static void BeginReceive()
    35.     {
    36.         socket.BeginReceive(new AsyncCallback(OnUdpData), socket);
    37.         Debug.Log("BeginRecvFunc");
    38.     }
    39.  
    40.     private static void OnUdpData(IAsyncResult result)
    41.     {
    42.         Debug.Log("OnUdpStart");
    43.         UdpClient socket = result.AsyncState as UdpClient;
    44.         IPEndPoint source = new IPEndPoint(0, 0);
    45.         byte[] message = socket.EndReceive(result, ref source);
    46.         string returnData = Encoding.ASCII.GetString(message);
    47.         Debug.Log("Data: " + returnData.ToString() + " from " + source);
    48.     }
    49. }


    I made it to call function only when the key is clicked but it doesn't even print: Debug.Log("OnUdpStart");
    what could be the problem? [as console app in Visual Studio it works well]. I turned off firewall for a moment and it didn't change anything.
     
    Last edited: Dec 6, 2020
  8. FakeByte

    FakeByte

    Joined:
    Dec 8, 2015
    Posts:
    147
    Which code did you use to send UDP messages to your UDP socket?
    If the packet is sent before you call BeginReceive it will be dropped, you can just call BeginReceive in the start function and then wait for a packet and then call BeginReceive again after receiving a packet, or in order not to miss packets you can even run multiple BeginReceive calls at the same time with different callbacks.
     
  9. p4rk3r0vsky

    p4rk3r0vsky

    Joined:
    Nov 3, 2020
    Posts:
    6
    I am using this app to send:
    https://play.google.com/store/apps/details?id=de.lorenz_fenster.sensorstreamgps

    'Console apps' which i have posted above works well, problem starts when I try to paste it into unity.
     
  10. p4rk3r0vsky

    p4rk3r0vsky

    Joined:
    Nov 3, 2020
    Posts:
    6
    anyone, anything? I have posted working consoleapp codes above - the only thing is just paste it correctly into unity - i still have no idea how to make it work xd
     
  11. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,445
    slampants and p4rk3r0vsky like this.
  12. p4rk3r0vsky

    p4rk3r0vsky

    Joined:
    Nov 3, 2020
    Posts:
    6
  13. slampants

    slampants

    Joined:
    Oct 27, 2013
    Posts:
    7