HoloLens TCP套接字无连接

时间:2019-01-10 19:34:01

标签: c# tcp stream hololens

我已经尝试了几天,以创建从HoloLens到我的本地计算机的TCP连接。我知道那里有很多解决方案,但是我不知道为什么我无法连接到设备。也许有人可以帮助我或告诉我我做错了什么。

到目前为止,这是我的代码

using UnityEngine;
#if WINDOWS_UWP
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Foundation;
#endif 

public class DataListener : MonoBehaviour
{
#if WINDOWS_UWP

  private StreamSocket _socket;
#endif

  private void Start()
  {
    SetupTcpConnection();
  }

  //HoloLens Code
  private void SetupTcpConnection()
  {
#if WINDOWS_UWP

    if (_socket != null)
      return;

    _socket = new StreamSocket();

    var hostName = new HostName("192.168.8.102");
    var socketConnectionAwaiter = _socket.ConnectAsync(hostName, "11000");
    var handler = new                     AsyncActionCompletedHandler(SocketConnectionCompleted);
socketConnectionAwaiter.Completed = handler;
#endif

  }
#if WINDOWS_UWP

  void SocketConnectionCompleted(IAsyncAction action, AsyncStatus status)
  {
    if (status != AsyncStatus.Completed)
    {
      _socket.Dispose();
      _socket = null;
      return;
    }

    // Read the data 
    using (var reader = new     StreamReader(_socket.InputStream.AsStreamForRead()))
    {
      var data = reader.ReadToEnd();

      //then read data

    }
  }
#endif

}

C#应用程序代码:

public static void StartClient3()
{
    var listener = new
    TcpListener(IPAddress.Any, 11000);
    var connectionHandler = new ConnectionHandler();

    var workerThread =
        new Thread(connectionHandler.HandleConnections);
    workerThread.Start(listener);

    while (!Console.KeyAvailable) { }

    Console.WriteLine("Shutting down");
    listener.Stop();
    workerThread.Abort();
}

public class ConnectionHandler
{
    TcpListener _listener;

    public void HandleConnections(object dataToPass)
    {

        _listener = dataToPass as TcpListener;
        if (_listener == null)
            return;

        _listener.Start();

        Console.WriteLine("We are waiting for a connection");
        while (true)
        {
            var client = _listener.AcceptTcpClient();

            Console.WriteLine("We are connected");

            var dataToSend = "SampleString";
            using (var writer = new StreamWriter(client.GetStream()))
            {
                writer.Write(dataToSend);
                writer.Flush();
            }
            client.Close();
        }
    }
}

我从本地计算机从ipconfig获取IP(192.168.8.102),所以这应该是正确的。 我不能简单地连接到HoloLens,也不知道为什么。

我还检查了Unity中的设置,例如InternetClientServer,PrivateNetworkClientServer,InternetClient。

有什么我忘记的事吗?非常感谢您的帮助!

拍。

0 个答案:

没有答案