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; , wss = new WebSocketServer({port: 9001}) , connects = [] wss.on('connection', function(ws) { connects.push(ws); ws.on('message', function(message) { console.log('received: %s', message); broadcast(message); }); ws.on('close', function () { console.log('stopping client send "close"'); connects = connects.filter(function (conn, i) { return (conn === ws) ? false : true; }); broadcast('connected sockets: ' + connects.length); }); // ws.send('something'); }); function broadcast (message) { connects.forEach(function (socket, i) { socket.send(message); }); }
起動
$ 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