Search code examples
hololens

unity udp dgram socket not working on hololens


I tried to connect between hololens and python server. So I used dgram socket but this is not working on hololens. this is my code sample.

hololens client

public string conHost = "192.168.0.58";
public int conPort = 3174;
 void Start()
    {
            ipep = new IPEndPoint(IPAddress.Parse(conHost), conPort);            
            clientThread = new Thread(setupSocket);
            clientThread.Start();
    }
public void setupSocket()
    {
        mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


    }
 void Update()
    {
        if(Send)
        {
                Send = false;                   
                byte[] bytes = Encoding.UTF8.GetBytes("124306324602435");
                byte[] buffer = Encoding.UTF8.GetBytes(bytes.Length.ToString());                   
                mySocket.SendTo(buffer, buffer.Length, SocketFlags.None, ipep);
        }
    }

python server

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#server_address = "192.168.0.18", 9029
#print('starting up on {} port {}'.format(*server_address))
sock.bind(("192.168.0.58", 3174))

ready=True
while(ready):        
    try:  
        epoch_time = time.time()
        data,address = sock.recvfrom(100)        
        fileLength = data.decode("utf-8")
        print(fileLength)
    except:                
        continue

When I play this code in unity project, it works. But in hololens, not working.

I used try-catch, I got this error messege on Update System.NullReferenceException: Object reference not set to an instance of an object [0x00000] in <000000000000000000000000000000000>:0


Solution

  • It occurs because the variable mySocket is not initialized as an expected value. Actually, the implementation of System.Threading has changed in .NET 4.x in a way that is not backward compatible, and the HoloLens app uses IL2CPP scripting backend with.NET4.x but the Unity Editor uses Mono scripting backend with.NET2.x. So, it works in Unity Editor but fails to start your thread in .NET4.x, we recommended that using System.Threading.Tasks class instead. Besides, to use WinRT APIs in Unity projects built for the UWP you need to use preprocessor directives, more information please see:WinRT APIs with Unity for HoloLens