Unity/websocket
websocket-sharpを使う
websocket-sharpをビルドする
- ruby2.0以上を入れる
- brew install mono
- Example〜Example4を削除しwebsocket-sharp.slnないのExampleも削除する
$ xbuild websocket-sharp.sln
- 以下が作成されることを確認
websocket-sharp/bin/Debug/websocket-sharp.dll
サーバ側websocketをインストール&起動
インストール
$ npm install -g ws
server.js作成
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port: 9001});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});
起動
$ node server.js
websocket(unity側)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using WebSocketSharp;
public class WebSocketScript : MonoBehaviour {
WebSocket ws;
void Start () {
this.ws = new WebSocket ("ws://localhost:9001");
this.ws.OnMessage += (object sender, MessageEventArgs e) => {
Debug.Log (e.Data);
};
this.ws.Connect ();
GameObject.Find("SendButton").GetComponent<Button>().onClick.AddListener(OnClickSend);
GameObject.Find("CloseButton").GetComponent<Button>().onClick.AddListener(OnClickClose);
}
void OnClickSend() {
this.ws.Send (System.DateTime.Now.ToString ());
}
void OnClickClose() {
this.ws.Close ();
}
}
参考
UnityでWebSocket通信 http://hwks.hatenadiary.jp/entry/2014/07/20/022229
websocket(サーバーサイド)サンプル http://kaworu.jpn.org/javascript/ws