win10 里使用 socket需要用 Windows.Networking下的类库实现,我们如果直接在Unity C# 脚本里 using Windows.Networking是不可以的,Unity编辑器在编译的时候是不能通过的。Windows.Networking 这是属于 WinRT API,只有在VS里才能被编译。
所以,如果要在Unity开发HoloLens程序使用 WinRT API 需要用 #if WINDOWS_UWP …… #endif 对相应的代码进行包裹,这样在Unity里就不会报错,build后再VS里再编译打包
可以尝试类似如下代码实现socket
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if WINDOWS_UWP
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
#endif
public class Socket : MonoBehaviour
{
#if WINDOWS_UWP
StreamSocket socket;
StreamSocketListener listener;
String port;
#endif
// Use this for initialization
void Start()
{
#if WINDOWS_UWP
listener = new StreamSocketListener();
port = "8888";
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.Control.KeepAlive = false;
Listener_Start();
#endif
}
#if WINDOWS_UWP
private async void Listener_Start()
{
Debug.Log("Listener started");
try
{
await listener.BindServiceNameAsync(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");
DataReader reader = new DataReader(args.Socket.InputStream);
try
{
while (true)
{
// Read first 4 bytes (length of the subsequent string).
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the string.
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringLength);
if (stringLength != actualStringLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// dump data
Debug.Log("Received: " + reader.ReadString(actualStringLength));
}
}
catch (Exception exception)
{
// If this is an unknown status it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
// dump data
Debug.Log("Read Stream failed: " + exception.Message);
}
}
#endif
// Update is called once per frame
void Update()
{
}
}