「Unity/websocket」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→websocket(unity側)) |
(→サーバ側websocketをインストール&起動) |
||
行14: | 行14: | ||
server.js作成 | server.js作成 | ||
var WebSocketServer = require('ws').Server; | var WebSocketServer = require('ws').Server; | ||
− | + | , wss = new WebSocketServer({port: 9001}) | |
+ | , connects = [] | ||
wss.on('connection', function(ws) { | wss.on('connection', function(ws) { | ||
− | + | connects.push(ws); | |
+ | ws.on('message', function(message) { | ||
console.log('received: %s', 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 | $ node server.js |
2017年11月16日 (木) 16:43時点における版
目次
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