如何通过套接字从UWP应用程序连接到Unity游戏服务器套接字?

我想将从微软乐队收到的一些心率值从UWP应用程序发送到Unity。 我目前在Unity中有一个工作的Tcp服务器,但我似乎无法在UWP中使用System.Net.Sockets。 任何人都知道如何在UWP应用程序上创建一个tcp客户端并将数据发送到Unity?

我的服务器代码如下:

using UnityEngine; using System.Collections; using System.Net.Sockets; using System.IO; using System.Net; using System.Threading; public class Server { public static TcpListener listener; public static Socket soc; public static NetworkStream s; public void StartService () { listener = new TcpListener (15579); listener.Start (); for(int i = 0;i < 1;i++){ Thread t = new Thread(new ThreadStart(Service)); t.Start(); } } void Service () { while (true) { soc = listener.AcceptSocket (); s = new NetworkStream (soc); StreamReader sr = new StreamReader (s); StreamWriter sw = new StreamWriter (s); sw.AutoFlush = true; while(true) { string heartrate = sr.ReadLine (); if(heartrate != null) { HeartRateController.CurrentHeartRate = int.Parse(heartrate); Debug.Log(HeartRateController.CurrentHeartRate); } else if (heartrate == null) { break; } } s.Close(); } } void OnApplicationQuit() { Debug.Log ("END"); listener.Stop (); s.Close(); soc.Close(); } } 

我的UWP代码如下:

  public IBandInfo[] pairedBands; public IBandClient bandClient; public IBandHeartRateReading heartreading; public MainPage() { this.InitializeComponent(); ConnectWithBand(); } public async void ConnectWithBand() { pairedBands = await BandClientManager.Instance.GetBandsAsync(); try { if (pairedBands.Length > 0) { bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]); } else { return; } } catch (BandException ex) { textBlock.Text = ex.Message; } GetHeartRate(); } public async void GetHeartRate() { IEnumerable supportedHeartBeatReportingIntervals = bandClient.SensorManager.HeartRate.SupportedReportingIntervals; bandClient.SensorManager.HeartRate.ReportingInterval = supportedHeartBeatReportingIntervals.First(); bandClient.SensorManager.HeartRate.ReadingChanged += this.OnHeartRateChanged; try { await bandClient.SensorManager.HeartRate.StartReadingsAsync(); } catch (BandException ex) { throw ex; } Window.Current.Closed += async (ss, ee) => { try { await bandClient.SensorManager.HeartRate.StopReadingsAsync(); } catch (BandException ex) { // handle a Band connection exception throw ex; } }; } private async void OnHeartRateChanged(object sender, BandSensorReadingEventArgs e) { var hR = e.SensorReading.HeartRate; await textBlock.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { textBlock.Text = hR.ToString(); }); } 

在做了一些研究之后,UWP没有System.Net.Sockets; 命名空间。 即使你设法在那里添加它,它也不会在编译后运行。 新的API称为StreamSocket套接字。 我从这里找到了一个完整的客户端示例,并对其进行了一些修改。 只需调用connect函数,发送和读取函数即可。

需要了解的重要一点是,您无法在同一台PC上运行此测试。 您的Unity服务器和UWP应用程序必须在不同的计算机上运行。 在使用UWP时,Microsoft不允许App连接到同一台计算机上的其他应用程序。

 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Windows.Networking; using Windows.Networking.Sockets; using Windows.Storage.Streams; namespace MyUniversalApp.Helpers { public class SocketClient { StreamSocket socket; public async Task connect(string host, string port) { HostName hostName; using (socket = new StreamSocket()) { hostName = new HostName(host); // Set NoDelay to false so that the Nagle algorithm is not disabled socket.Control.NoDelay = false; try { // Connect to the server await socket.ConnectAsync(hostName, port); } catch (Exception exception) { switch (SocketError.GetStatus(exception.HResult)) { case SocketErrorStatus.HostNotFound: // Handle HostNotFound Error throw; default: // If this is an unknown status it means that the error is fatal and retry will likely fail. throw; } } } } public async Task send(string message) { DataWriter writer; // Create the data writer object backed by the in-memory stream. using (writer = new DataWriter(socket.OutputStream)) { // Set the Unicode character encoding for the output stream writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // Specify the byte order of a stream. writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Gets the size of UTF-8 string. writer.MeasureString(message); // Write a string value to the output stream. writer.WriteString(message); // Send the contents of the writer to the backing stream. try { await writer.StoreAsync(); } catch (Exception exception) { switch (SocketError.GetStatus(exception.HResult)) { case SocketErrorStatus.HostNotFound: // Handle HostNotFound Error throw; default: // If this is an unknown status it means that the error is fatal and retry will likely fail. throw; } } await writer.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter writer.DetachStream(); } } public async Task read() { DataReader reader; StringBuilder strBuilder; using (reader = new DataReader(socket.InputStream)) { strBuilder = new StringBuilder(); // Set the DataReader to only wait for available data (so that we don't have to know the data size) reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.Partial; // The encoding and byte order need to match the settings of the writer we previously used. reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; reader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Send the contents of the writer to the backing stream. // Get the size of the buffer that has not been read. await reader.LoadAsync(256); // Keep reading until we consume the complete stream. while (reader.UnconsumedBufferLength > 0) { strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength)); await reader.LoadAsync(256); } reader.DetachStream(); return strBuilder.ToString(); } } } }