チラ裏Unity

主にUnityについての備忘録ですが誰か様の為になれば

UnityでWebSocket通信

node.jsのインストール

http://nodejs.org/

  1. http://nodejs.org/download にアクセス
  2. Mac OS X Installer (.pkg) をダウンロードしてインストール

 

wsモジュールのインストール

http://einaros.github.io/ws/

  1. $ npm install -g ws
    • -gでグローバルにインストールしています
    • 必要であればsudo付で実行します
  2. 以下の環境変数を追加
    export NODE_PATH=/usr/local/lib/node_modules

 

websocket-sharpのインストール

http://sta.github.io/websocket-sharp/

  1. $ git clone https://github.com/sta/websocket-sharp.git
  2. websocket-sharp.sln を開く(以降MonoDevelop-Unityを前提)
  3. ソリューションからwebsocket-sharpを右クリックしてビルド
    • Exampleはビルドしない
  4. /websocket-sharp/websocket-sharp/bin/Debug/websocket-sharp.dllをUnityプロジェクトのAssets/Pluginsにコピー

 

WebSocketサーバを立ち上げる

  1. 以下のようなWebSocket用サーバjsファイルを適当な場所に作成
    $ vi server.js
    var WebSocketServer = require('ws').Server
    , wss = new WebSocketServer({port: 8080});
    wss.on('connection', function(ws) {
    ws.on('message', function(message) {
    console.log('received: %s', message);
    });
    ws.send('something');
    });
  2. $ node server.js

 

WebSocketクライアントをUnityで立ち上げる

  1. 以下のようなスクリプトを適当なGameObjectにアタッチして実行
    using UnityEngine;
    using WebSocketSharp;

    public class WebSocketClient : MonoBehaviour {
        
        private WebSocket ws;
        
        void OnGUI() {
            if (GUILayout.Button("Connect")) {
                this.ws = new WebSocket("ws://127.0.0.1:8080");
                this.ws.OnMessage += (object senderMessageEventArgs e) => {
                    print (e.Data);
                };
                this.ws.Connect ();
            }
            
            if (GUILayout.Button("Send")) {
                this.ws.Send (System.DateTime.Now.ToString ());
            }
            
            if (GUILayout.Button("Close")) {
                this.ws.Close ();
            }
        }
    }
  2. Connectボタンを押すとWebSocketサーバ(node.js+ws)に接続し、Console上にsomethingと表示される
  3. Sendボタンを押すとターミナル上に現在日時が以下のように表示される
    received: 07/20/2014 01:57:28
  4. Closeボタンを押すとWebSocketサーバと切断する

 

まとめ

ミニマムな環境構築と動作確認は驚くほど簡単

 

補足

iOSAndroidへのビルドはProのみのようです

Unity5からPersonal(無料版)でもビルドが出来るようになったようです

  • Error building Player: SystemException: 'System.Net.Sockets' are supported only with Unity Android Pro. Referenced from assembly 'websocket-sharp'.
  • Error building Player: SystemException: System.Net.Sockets are supported only on Unity iOS Pro. Referenced from assembly 'websocket-sharp'.

 

socket.io モジュールを使った実装も参考までに