Unity3d script to connect to NodeJS using WebSocketSharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System; | |
using System.Security.Policy; | |
using System.Threading; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
using WebSocketSharp; | |
using WebSocketSharp.Net; | |
using System.Collections.Generic; | |
public class LittlebitsNode : LittlebitsData { | |
// receiving Thread | |
Thread receiveThread; | |
private string uri = "ws://192.168.1.12:8001"; | |
//private string uri = "ws://192.168.43.139:8001"; | |
WebSocket ws; | |
// Use this for initialization | |
void Start () { | |
init (); | |
} | |
private void init() | |
{ | |
// ---------------------------- | |
// Abhören | |
// ---------------------------- | |
// Lokalen Endpunkt definieren (wo Nachrichten empfangen werden). | |
// Einen neuen Thread für den Empfang eingehender Nachrichten erstellen. | |
receiveThread = new Thread( | |
new ThreadStart(ReceiveData)); | |
receiveThread.IsBackground = true; | |
receiveThread.Start(); | |
} | |
private void ReceiveData() | |
{ | |
ws = new WebSocket (uri); | |
{ | |
// Set the WebSocket events. | |
ws.OnOpen += (sender, e) => | |
{ | |
}; | |
ws.OnMessage += (sender, e) => | |
{ | |
Debug.Log(e.Data); | |
var data = e.Data.Split(':'); | |
if (data[0] == "slide") | |
{ | |
value = Convert.ToSingle(data[1]); | |
Debug.Log (value); | |
} | |
}; | |
ws.OnError += (sender, e) => | |
Debug.Log ("Error >>" + e.Message); | |
ws.OnClose += (sender, e) => | |
Debug.Log(String.Format("WebSocket Close ({0})", e.Code)); | |
#if DEBUG | |
// To change the logging level. | |
ws.Log.Level = LogLevel.Trace; | |
// To change the wait time for the response to the Ping or Close. | |
ws.WaitTime = TimeSpan.FromSeconds(10); | |
// To emit a WebSocket.OnMessage event when receives a ping. | |
ws.EmitOnPing = true; | |
#endif | |
} | |
ws.ConnectAsync (); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment