Skip to content

Instantly share code, notes, and snippets.

@rondagdag
Created December 22, 2015 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondagdag/e7c4324cf97fb8030322 to your computer and use it in GitHub Desktop.
Save rondagdag/e7c4324cf97fb8030322 to your computer and use it in GitHub Desktop.
Unity3d script to connect to NodeJS using WebSocketSharp
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