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 !

Sign In or Register to comment.