Hololens UDP server?

Hello,

I'm trying to build a simple UDP server to run on the Hololens. However, I'm getting the error:
The type or namespace name 'UdpClient' could not be found (are you missing a using directive or an assembly reference?)

Here's the code:

using UnityEngine;
using System.Net;
using System.Net.Sockets;

public class AndroidUDPListener : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Debug.Log("Waiting for a connection...", gameObject);

        UdpClient udpServer = new UdpClient(12345);

        var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
        var data = udpServer.Receive(ref remoteEP); // listen on port 11000
        Debug.Log("receive data from: " + remoteEP.ToString(), gameObject);
        Debug.Log("data: " + data, gameObject);
    }

    // Update is called once per frame
    void Update () {

    }
}

I'm following the code from this example:
http://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket

Additionally, Visual Studio seems to think the "using System.Net.Sockets;" directive isn't necessary. Can anyone please help? Thank you

Best Answer

Answers

  • Thank you, Patrick!

    The #if / #endifs in the tutorial code were the key to solving this problem. Here's the working code I ended up with:

    using UnityEngine;
    using System;
    using System.IO;
    
    #if !UNITY_EDITOR
    using Windows.Networking.Sockets;
    #endif
    
    public class AndroidUDPListener : MonoBehaviour {
    #if !UNITY_EDITOR
        DatagramSocket socket;
    #endif
        // use this for initialization
        async void Start()
        {
    #if !UNITY_EDITOR
            Debug.Log("Waiting for a connection...");
    
            socket = new DatagramSocket();
            socket.MessageReceived += Socket_MessageReceived;
    
            try
            {
                await socket.BindEndpointAsync(null, "12345");
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
                Debug.Log(SocketError.GetStatus(e.HResult).ToString());
                return;
            }
    
            Debug.Log("exit start");
    #endif
        }
    
        // Update is called once per frame
        void Update ()
        {
    
        }
    
    #if !UNITY_EDITOR
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
            Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            //Read the message that was received from the UDP echo client.
            Stream streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader = new StreamReader(streamIn);
            string message = await reader.ReadLineAsync();
    
            Debug.Log("MESSAGE: " + message);
        }
    #endif
    }
    
  • Hello,

    I am trying to make an app for the hololens which needs to receive data from a server. I already have installed all the latest tools and did all the tutorials but when I try to add the above code in visual studio (as the editor for the scrips) I get a message "Feature 'async function' is not available in C#4. Please use language version 5 or greater.".
    Because the solution in visual studio has no properties I edited the csproj file to target framework 4.5.2 and langVersion changed to 5. This stopped the message from showing but I still cannot add the script to a component in Unity. Also I get the following error in Unity:
    error CS1519: Unexpected symbol `void' in class, struct, or interface member declaration

    Any idea how to solve this?

    regards,
    Jeroen

  • Hi @JeroenDeDeken,
    Unity does not support .Net 4.5, so you won't be able to target that framework. Also, be sure to use #if !UNITY_EDITOR like in the code sample earlier, as you won't be able to call async methods while running in Unity.

    If you want to divide work across multiple frames when running in Unity, then you'll need to use coroutines instead.

  • edited July 2016

    @ahillier
    I see what you mean but method Start is mentioned as async and this gives problems with the compiler so I was wondering how this code is used. For now I added:

    #if UNITY_EDITOR
        void Start()
        {
    #endif
    #if !UNITY_EDITOR
        async void Start()
        {
    

    I am not sure if this is the way to go but it seems to do the job.

  • edited October 2016

    I was finally able to get UDP communication working with the HoloLens with the code above. The problam was that "Private Networks (Client & Server)" capability was missing from the manifest (this is set in the publishing settings in Unity)

    Then it seemed that the application crashes whenever an UDP message is received, and I thought the problem is in the code, but it turned out that it was because I was trying to update my UI from the Socket_MessageReceived. I noticed "get_isActiveAndEnabled can only be called from the main thread." error in the VS output window and then realized that I need to do the following:

    UnityEngine.WSA.Application.InvokeOnAppThread(() =>
    {
    //change your Holoapp GUI or whatever here
    }, false);

  • lsplsp
    edited December 2016

    the manifest file! thanks, lost one day trying to send data via UDP from the device to the PC. Now it works.

  • Hi everyone! I used this topic to create a hololens app which can receive message from a nodejs udp client. However even if the udp server runs, it never receives the client's message. Here is my complete code : http://stackoverflow.com/questions/44034118/hololens-udp-server-never-receives-message If someone has an idea? Thanks !

  • I have built a working UWP application consisting of a server and client multicasting UDP. I want to use this for simple scene management in the hololens. It works perfectly well on PC (it is UWP) and should work fine on Hololens. But it does not.

    I have used Wireshark to view the network and indeed the correct UDP packets are being sent. There seems to be a firewall or something blocking it on the Hololens part. I have added the capabilities (Client&Server internet AND private networks) to no avail.

    This is supposed to be a developer edition. It doesnt really live up to its name so far.

    Does anyone have an idea what might be wrong?

  • @sebrk This can happens for multiple reason, you can try to wath this post. This happens when you are running the emulator. In Hololens you can see multiple samples that run. i also experience a problem communicating 4.5 framework with UWP. You can take a look here.
    Hope it helps

  • @DiegoV said:
    @sebrk This can happens for multiple reason, you can try to wath this post. This happens when you are running the emulator. In Hololens you can see multiple samples that run. i also experience a problem communicating 4.5 framework with UWP. You can take a look here.
    Hope it helps

    I'm not running the emulator. This is on device. As I also said it works fine with a Windows application and I can clearly see my UDP packets on the network. I'm sort of amazed by this. Clearly the Hololens has some sort of firewall which does not work properly.

    Your second link doesn't lead anywhere?

  • What I was trying to explain you , is that with big packets Hololens do not works propoertly. I do not think there is any blocking thing. I have communicated with WCF with no issues.

  • sebrksebrk
    edited July 3

    @DiegoV said:
    What I was trying to explain you , is that with big packets Hololens do not works propoertly. I do not think there is any blocking thing. I have communicated with WCF with no issues.

    My packets are 199 bytes. If that is considered big I don't know what year this is.

    Would you please share your code?

    If it wasn't clear before, I specifically need to use UDP and multicast. I should say that the Hololens does SEND a JOIN message so communicating outwards works fine. It is sending TO the Hololens that doesn't work. Thanks.

  • oh, I never tried with Multicast :neutral: I am sorry

  • Can't even get the Hololens UNET sharing to work. It just searches for server all the time, even though I can see packets. Horrible device.

  • @vigiljt said:
    Thank you, Patrick!

    The #if / #endifs in the tutorial code were the key to solving this problem. Here's the working code I ended up with:

    using UnityEngine;
    using System;
    using System.IO;
    
    #if !UNITY_EDITOR
    using Windows.Networking.Sockets;
    #endif
    
    public class AndroidUDPListener : MonoBehaviour {
    #if !UNITY_EDITOR
        DatagramSocket socket;
    #endif
        // use this for initialization
        async void Start()
        {
    #if !UNITY_EDITOR
            Debug.Log("Waiting for a connection...");
        
            socket = new DatagramSocket();
            socket.MessageReceived += Socket_MessageReceived;
    
            try
            {
                await socket.BindEndpointAsync(null, "12345");
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
                Debug.Log(SocketError.GetStatus(e.HResult).ToString());
                return;
            }
    
            Debug.Log("exit start");
    #endif
        }
    
        // Update is called once per frame
        void Update ()
        {
    
        }
    
    #if !UNITY_EDITOR
        private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender,
            Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
        {
            //Read the message that was received from the UDP echo client.
            Stream streamIn = args.GetDataStream().AsStreamForRead();
            StreamReader reader = new StreamReader(streamIn);
            string message = await reader.ReadLineAsync();
    
            Debug.Log("MESSAGE: " + message);
        }
    #endif
    }
    

    I've tried this as well. I want an Android device sending simple strings to the Hololens. Nothing works. I can clearly see the messages on the network but the Hololens never picks it up. Can you share your full code please?

  • @sebrk Any luck? I run into the same problem.

Sign In or Register to comment.