简体   繁体   中英

TCP connection between hololens 2 and a unity app on computer only works once

I tried to build TCP connection between hololens 2 and an unity app on PC. Now it can work once, but then the connection is failed. I really don't know why.

Hololens is server and unity app on PC is client. when failed, a message in unity app is "SocketException: An existing connection was forcibly closed by the remote host." and I try to capture information in hololens 2, too. It shows " A device disconnection with the id 20000000068 has been reported but no device with that id was connect.

My server code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

#if !UNITY_EDITOR
    using Windows.Networking;
    using Windows.Networking.Sockets;
    using Windows.Storage.Streams;
#endif

//Able to act as a reciever 
public class UniversalSampleTutorial : MonoBehaviour
{
    public String _input = "Waiting";

#if !UNITY_EDITOR
        StreamSocket socket;
        StreamSocketListener listener;
        String port;
        String message;
#endif

    // Use this for initialization
    void Start()
    {
#if !UNITY_EDITOR
        listener = new StreamSocketListener();
        port = "9090";
        listener.ConnectionReceived += Listener_ConnectionReceived; // This means one connection build, whenever event will be triggered 
        listener.Control.KeepAlive = true; // control is like setting for streamsocket object, keep alive means constantly sending data, when no data, can send keep alive packet

        Listener_Start();
#endif
    }

#if !UNITY_EDITOR
    private async void Listener_Start()
    {
        Debug.Log("Listener started");
        try
        {
            await listener.BindServiceNameAsync(port); // start to listening to a port
        }
        catch (Exception e)
        {
            Debug.Log("Error: " + e.Message);
        }

        Debug.Log("Listening");
    }

    private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        Debug.Log("Connection received");

        try
        {
            while (true) {

                    using (var dw = new DataWriter(args.Socket.OutputStream)) // args is a connection, that for the connection, we have sockets, and then you can write, use once
                    {
                        dw.WriteString("Hello There");
                        await dw.StoreAsync();  // buffer data to stream
                        await dw.FlushAsync();
                        dw.DetachStream();
                    }  

                    using (var dr = new DataReader(args.Socket.InputStream))
                    {
                        dr.InputStreamOptions = InputStreamOptions.Partial;
                        await dr.LoadAsync(12);
                        var input = dr.ReadString(12);
                        Debug.Log("received: " + input);
                        _input = input;
                    }
            }
        }
        catch (Exception e)
        {
            Debug.Log("disconnected!!!!!!!! " + e);
        }

    }

#endif

    void Update()
    {
        this.GetComponent<TextMeshProUGUI>().text = _input;
    }
} 

My client code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class UnityClient : MonoBehaviour
{
    public string IP;
    public int port;
    public string GoHololens;
    private TcpClient client;
    private Thread clientReceiveThread;
    private void Start()
    {
        ConnectToTcpServer();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            SendMessage();
        }
    }



    private void ConnectToTcpServer()
    {
        try
        {
            clientReceiveThread = new Thread(new ThreadStart(ListenForData));
            clientReceiveThread.IsBackground = true; // set this thread is background thread or not
            clientReceiveThread.Start();
        }
        catch (Exception _ex)
        {
            Debug.Log("Faild to connect:" + _ex);
        }
    }

    private void ListenForData()
    {
        try
        {
            client = new TcpClient(IP, port);
            Byte[] bytes = new Byte[1024];
            while (true)
            {
                // get stream object for reading
                using(NetworkStream stream = client.GetStream())
                {
                    int length;
                    while((length=stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        var incomingData = new byte[length];
                        Array.Copy(bytes, 0, incomingData, 0, length);

                        string serverMessage = Encoding.ASCII.GetString(incomingData);
                        Debug.Log("server Message received as:" + serverMessage);
                    }
                }
            }
        }
        catch (SocketException socketExcep)
        {
            Debug.Log("socket exception:" + socketExcep);
        }

    }

    private void SendMessage()
    {
        if(client == null)
        {
            Debug.Log("No tcp client exist");
            return;
        }

        try
        {
            NetworkStream stream = client.GetStream();
            if (stream.CanWrite)
            {
                string clientMessage = GoHololens;
                byte[] clientMessageAsByteArray = Encoding.ASCII.GetBytes(clientMessage);

                stream.Write(clientMessageAsByteArray, 0, clientMessageAsByteArray.Length);
                Debug.Log("client send message");
            }
        }
        catch (SocketException socketExcep)
        {
            Debug.Log("Socket exception:" + socketExcep);
        }

    }
}

We have verified the following C# unity code without streams wrappers attaching to the socket streams in it.

while (true) {
byte[] outdata = new byte[256];

//ABCDE
outdata[0] = 65;
outdata[1] = 66;
outdata[2] = 67;
outdata[3] = 68;
outdata[4] = 69;

var outbuffer = outdata.AsBuffer();
await args.Socket.OutputStream.WriteAsync(outbuffer);


byte[] data = new byte[256];
IBuffer buffer = data.AsBuffer();
uint bytesRead =12;


await args.Socket.InputStream.ReadAsync(buffer, bytesRead, Windows.Storage.Streams.InputStreamOptions.None);
var input = System.Text.Encoding.UTF8.GetString(buffer.ToArray());

Debug.Log("received: " + input);
_input = input;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM