issac1222
issac1222

Reputation: 1

Hololens 2 Emulator Unity TCP connection - socket connects properly but no data is transmitted?

I'm having trouble with getting a TCP connection working and sending data from a Python script running on a machine on the same network to a Unity app on the Hololens 2 Emulator. At this point, I know from testing that I can get the python script to properly connect to the emulator as socket.connect(server_address) as well as sock.sendall(message) work.

On the Emulator side of things, the code seems to hang on the line

using (connectedTcpClient = tcpListener.AcceptTcpClient())

as no other breakpoints and/or print statements past that point in the code are ever hit.

Here is the python script I'm using:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('192.168.1.152', 9090)
print('connecting to {} port {}...'.format(*server_address))
sock.connect(server_address)

try:

    # Send data
    message = b'Hello World!'
    print('sending {!r}'.format(message))
    sock.sendall(message)
    print('message sent, waiting...')

    # Look for the response
    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print('received {!r}'.format(data))

finally:
    print('closing socket')
    sock.close()

And here is the C# app running on the Hololens Emulator in Unity:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using TMPro;
using UnityEngine;
using UnityEngine.UIElements;

public class TCPyManager : MonoBehaviour
{
    #region private members     
    /// <summary>   
    /// TCPListener to listen for incoming TCP connection   
    /// requests.   
    /// </summary>  
    private TcpListener tcpListener;
    /// <summary> 
    /// Background thread for TcpServer workload.   
    /// </summary>  
    private Thread tcpListenerThread;
    /// <summary>   
    /// Create handle to connected tcp client.  
    /// </summary>  
    private TcpClient connectedTcpClient;

    private string clientMessage;
    private string status;
    private string data;

    public TMP_Text statusText;
    public TMP_Text dataText;

    #endregion

    // Use this for initialization
    void Start()
    {
        // Start TcpServer background thread        
        tcpListenerThread = new Thread(new ThreadStart(ListenForIncomingRequests));
        tcpListenerThread.IsBackground = true;
        tcpListenerThread.Start();
    }

    // Update is called once per frame
    void Update()
    {
        //if (Input.GetKeyDown(KeyCode.Space))
        //{
        //    dataText.SetText(clientMessage);
        //}
        statusText.SetText(status);
        dataText.SetText(data);
    }

    /// <summary>   
    /// Runs in background TcpServerThread; Handles incoming TcpClient requests     
    /// </summary>  
    private void ListenForIncomingRequests()
    {
        try
        {
            // Create listener on raspi IP address port 9090.           
            tcpListener = new TcpListener(IPAddress.Parse("192.168.1.152"), 9090);
            tcpListener.Start();
            data = "Waiting...";
            //Debug.Log("Server is listening");
            status = "Server is listening";
            Byte[] bytes = new Byte[16];
            while (true)
            {
                status = "Waiting for client";
                Thread.Sleep(10);
                using (connectedTcpClient = tcpListener.AcceptTcpClient())
                {

                    //connectedTcpClient = tcpListener.AcceptTcpClient();
                    //if (connectedTcpClient != null)
                    //{
                    //    status = "Client accepted";
                    //}

                    status = "Client accepted";
                    //Get a stream object for reading
                    using (NetworkStream stream = connectedTcpClient.GetStream())
                    {

                        //NetworkStream stream = connectedTcpClient.GetStream();

                        //status = "Stream connected";
                        int length;
                        // Read incoming stream into byte arrary.                       
                        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            //var incomingData = new byte[length];
                            //Array.Copy(bytes, 0, incomingData, 0, length);
                            // Convert byte array to string message.                            
                            clientMessage = System.Text.Encoding.ASCII.GetString(bytes, 0, length);
                            //Debug.Log("client message received as: " + clientMessage);
                            status = "Message received!";
                            data = clientMessage;
                            SendMessage(clientMessage);
                            //stream.Flush();
                        }
                        //}
                        //}
                    }
                }
            }
        }
        catch (SocketException socketException)
        {
            //Debug.Log("SocketException " + socketException.ToString());
            status = "SocketException " + socketException.ToString();
        }
    }
    /// <summary>   
    /// Send message to client using socket connection.     
    /// </summary>  
    private void SendMessage(string message)
    {
        if (connectedTcpClient == null)
        {
            return;
        }

        try
        {
            // Get a stream object for writing.             
            NetworkStream stream = connectedTcpClient.GetStream();
            if (stream.CanWrite)
            {
                string serverMessage = message;
                // Convert string message to byte array.                 
                byte[] serverMessageAsByteArray = System.Text.Encoding.ASCII.GetBytes(serverMessage);
                // Write byte array to socketConnection stream.               
                stream.Write(serverMessageAsByteArray, 0, serverMessageAsByteArray.Length);
                //Debug.Log("Server sent message - should be received by client");
                status = "Server sent message - should be received by client";
            }
        }
        catch (SocketException socketException)
        {
            //Debug.Log("Socket exception: " + socketException);
            status = "SocketException " + socketException.ToString();
        }
    }
}

I've tried running the Python script on the same machine as the one running the Emulator and switching the IP address to 127.0.0.1 / localhost. The same problem as before comes up; the python script connects to the server and tries to deliver the string message but it just doesn't make it through to the emulator. I've tried replacing the IP address in the script with that of the emulator's. This didn't work; the script wasn't able to even connect to it. I have InternetClient, InternetClientServer, and PrivateNetworkClientServer all selected in my Unity player settings. I've also set up the TCP server port in the emulator following Microsoft's guide. At this point I'm not sure what's going wrong.

Upvotes: 0

Views: 64

Answers (0)

Related Questions