2016-05-18 43 views
1

Microsoft BandからUWPアプリケーションからUnityに受け取った心拍数をいくつか送付したいと思います。私は現在ユニティでTcp Serverを稼働していますが、UWPでSystem.Net.Socketsを使用することはできませんでした。誰でもUWPアプリケーションでTCPクライアントを作成し、そのデータをUnityに送信する方法を知っていますか?次のようにUWPアプリからUnity経由で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<TimeSpan> supportedHeartBeatReportingIntervals = bandClient.SensorManager.HeartRate.SupportedReportingIntervals; 
     bandClient.SensorManager.HeartRate.ReportingInterval = supportedHeartBeatReportingIntervals.First<TimeSpan>(); 

     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<IBandHeartRateReading> e) 
    { 
     var hR = e.SensorReading.HeartRate; 
     await textBlock.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low,() => 
     { 
      textBlock.Text = hR.ToString(); 
     }); 
    } 
+1

ご質問はありません。投稿したUnityサーバコードの代わりに 'TcpListner'を使用することにしたので、あなたが書いたサーバコードが動作していると思いますか?クライアントコードを作成する前にテストしましたか?私は、サーバをテストせずにクライアントで作業するのは時間の無駄だろうと思う。サーバーのテスト方法がわからない場合はお知らせください。 – Programmer

+0

@Programmer、私はGeneric BLE心拍モニタから心拍数を取得したクライアントと接続していた別のプロジェクトに同じサーバーを使用していました。それは完璧に働いた。これは1年前にStakeoverflowに投稿したコードだった:http://stackoverflow.com/questions/30161845/unity-delay-in-sending-the-current-value-when-using-sockets – ChaosEmperor93

+0

Ok good 。以前私も同様の質問に答えてきたと思います。 http://stackoverflow.com/a/35890916/3785314私はその人のためのコードを提供していません。今あなたのUWPプログラムで 'TcpClient'を動作させる必要がありますか?以前はUWPを使ったことがありません。 'System.Net.Sockets;'名前空間は利用できますか? – Programmer

答えて

1

いくつかの研究を行った後、UWPはSystem.Net.Sockets;名前空間を持っていませありません。たとえそれを追加して管理しても、コンパイル後には実行されません。新しいAPIはStreamSocketソケットと呼ばれます。私はhereから完全なクライアントの例を見つけて少し修正しました。 connect関数、send関数、read関数を呼び出してください。

重要なことは、このテストを同じPCで実行できないことです。ユニティサーバとUWPアプリケーションは別々のコンピュータで動作しているに違いありません。マイクロソフトではではありません。は、UWPを使用している場合、同じコンピュータ上の別のアプリケーションにアプリケーションを接続できます。

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<String> 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(); 
      } 
     } 
    } 
} 
+0

ああ。私はそれが本当であることがあまりにも良いことを知っていた。残念ながら、それは私のための選択肢ではありません。私はそれが地元に必要です。私は1週間ほどでゲームを見せてくれるが、インターネットアクセスは保証できない。 – ChaosEmperor93

+0

@ ChaosEmperor93 **これは現地**です。同じルータ/ネットワーク.wifiに接続する必要があります。これを理解していませんか?そして、いいえ。**これにはインターネットは必要ありません**。両方が同じネットワークに接続されていることを確認してください。シンプルなルータをお持ちでない場合は、購入することができます。 – Programmer

+0

申し訳ありません私は上記のあなたのコメントを読む前にコメントを投稿しました。問題は、私のゲームがマルチプレイヤー機能を持っているので、おそらく遅れがあるということです。マルチプレイヤーでは、心拍数モニタリングを引き続き使用するオプションがあります。将来的にはこれは私の必要条件とうまくいっていません – ChaosEmperor93

関連する問題