リアルとバーチャルの間

気まぐれに書いてます。

【メモ】Unityでwebsocketsする

凹みさんの記事を参考にしました。
色々な技術を記事にしてくれていて本当にすごいなあ。

tips.hecomi.com

こちらからpackageを落とせます。
Unity5 Beta : WebGL + Unity WebSockets plug-in | Unity Community
リンク切れしていたらこちらからダウンロードしてみてください。

パッケージを入れたら、以下を記入します。

using UnityEngine;
using System.Collections;
using System;

public class EchoTest : MonoBehaviour {

	// Use this for initialization
	IEnumerator Start () {
		WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:3000"));
		yield return StartCoroutine(w.Connect());
		w.SendString("Hi there");
		int i=0;
		while (true)
		{
			string reply = w.RecvString();
			if (reply != null)
			{
				Debug.Log ("Received: "+reply);
				w.SendString("Hi there"+i++);
			}
			if (w.Error != null)
			{
				//Debug.LogError ("Error: "+w.Error);
				break;
			}
			yield return 0;
		}
		w.Close();
	}
}

ターミナルでwsのモジュールを入れます。
(nodeを入れているのが前提条件です)

npm install ws

server.jsを作り。

var ws = require('ws').Server;

var server = new ws({ port: 3000 });
server.on('connection', function(ws) {
    console.log('connected!');
    ws.on('message', function(message) {
        console.log(message.toString());
    });
    ws.on('close', function() {
        console.log('disconnected...');
    });
    setInterval(function() {
        ws.send("Hi!");
    }, 1000);
});

ターミナルからcdで指定のディレクトリへ移動した後。
node server.jsを実行すればよい。

server.jsでやっている事は簡単に言うと以下のような感じ。
ws.on Unityから送られてきたデータを受け取っている。
ws.send Unityへデータを送る。