LoginSignup
113
108

More than 5 years have passed since last update.

UnityでWebSocketを使用する

Last updated at Posted at 2015-11-05

1. C# WebSocketライブラリのダウンロード

使用するライブラリ
websocket-sharp
https://github.com/sta/websocket-sharp

websocket-sharpのgithubページに移動し、ファイルをダウンロード

スクリーンショット 2015-11-05 17.40.50-01.png

2. C# WebSocketライブラリのビルド

Macの場合、
websocket-sharpフォルダ内の
websocket-sharp.slnファイルをダブルクリックする。

ws_000.png

① websocket-sharpソリューションファイルを開く

Unityをインストールして.slnファイルの扱いについての何も設定を行っていなければ、MonoDevelopが立ち上がります。
ビルドにはMonoDevelopを使用することにします。

② 不要なプロジェクトの削除

このままビルドすると、サブプロジェクトであるExampleXXプロジェクト部分でエラーが出力されるので、それらをソリューションから削除しておきます。(実際、エラーは気にしなくても大丈夫です)

メニューから メニュー>Visual Designを選択し、サイドバーにプロジェクト一覧を表示

Example, Example1, Example2, Example3を選択し、

右のツールボタンから、削除を選択
Removeをクリック

スクリーンショット 2015-11-05 19.13.57.png

③ ビルド方法をReleaseに変更

④ メニューから ビルド>全てをビルド を実行

ビルドに成功すると、
websocket-sharp/bin/ ディレクトリに、Release/websocket-sharp.dll ファイルが作成されます。
ws_001.png

3. Unityにwebsocket-sharpライブラリを読み込む

先ほどビルドした websocket-sharp.dllファイルを Assets直下にPluginsフォルダを作り、その下に置きます。
スクリーンショット 2015-11-05 18.12.22.png

4. サンプルコード

① クライアント (Unity)

シンプルなWebSocketクライアントプログラムです。
変数 WSAddress には接続先のWebSocketサーバアドレスを記述します。
スペースキーを押すと、Test Message というWebSocketメッセージを送信します。

ClientExample.cs
using UnityEngine;
using System.Collections;
using WebSocketSharp;
using WebSocketSharp.Net;

public class ClientExample: MonoBehaviour {

    WebSocket ws;

    void Start()
    {
        ws = new WebSocket("ws://localhost:3000/");

        ws.OnOpen += (sender, e) =>
        {
            Debug.Log("WebSocket Open");
        };

        ws.OnMessage += (sender, e) =>
        {
            Debug.Log("WebSocket Message Type: " + e.Type + ", Data: " + e.Data);
        };

        ws.OnError += (sender, e) =>
        {
            Debug.Log("WebSocket Error Message: " + e.Message);
        };

        ws.OnClose += (sender, e) =>
        {
            Debug.Log("WebSocket Close");
        };

        ws.Connect();

    }

    void Update()
    {

        if (Input.GetKeyUp("s"))
        {
            ws.Send("Test Message");
        }

    }

    void OnDestroy()
    {
        ws.Close();
        ws = null;
    }
}

② サーバーサイド (Unity)

ポート3000番で、メッセージが来たらそのままそのメッセージをブロードキャストするシンプルなサーバープログラムです。

ServerExample.cs
using UnityEngine;
using System.Collections;
using WebSocketSharp;
using WebSocketSharp.Net;
using WebSocketSharp.Server;

public class ServerExample: MonoBehaviour {

    WebSocketServer server;

    void Start ()
    {
        server = new WebSocketServer(3000);

        server.AddWebSocketService<Echo>("/");
        server.Start();

    }

    void OnDestroy()
    {
        server.Stop();
        server = null;
    }

}

public class Echo : WebSocketBehavior
{
    protected override void OnMessage (MessageEventArgs e)
    {
        Sessions.Broadcast(e.Data);
    }
}

(補足) サーバーサイド (Node.js)

ポート3000番で、メッセージが来たらそのままそのメッセージをブロードキャストするシンプルなNode.jsサーバープログラムです。

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

var wss = new ws ({port: 3000});


wss.broadcast = function (data) {
    for (var i in this.clients) {
        this.clients [i].send (data);
    }
};

wss.on ('connection', function (ws) {
    ws.on ('message', function (message) {
        var now = new Date();
        console.log (now.toLocaleString() + ' Received: %s', message);
        wss.broadcast (message);
    });
});
113
108
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
113
108