1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity/WebSocket

Last updated at Posted at 2022-02-18

ご参考

手順1 [websocket-sharp.dll]をビルドする。

VisualStudio2019 でビルドするとエラーが出る。これはJsonsoftなど必要なライブラリがないため。
image.png

Nugetで[Newtonsoft]を追加する
image.png

image.png

手順2 Unityプロジェクトに[websocket-sharp.dll]を追加、動作確認を行う。


using UnityEngine;
using System.Collections;
using WebSocketSharp;
using WebSocketSharp.Server;
public class ExampleWebSocketServer : MonoBehaviour {

    public static int port = 5678;
    private WebSocketServer server;

    void Start()
    {
        server = new WebSocketServer(port);
        server.AddWebSocketService<Echo>("/");
        server.Start();

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

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



using UnityEngine;
using System.Collections;
using WebSocketSharp;

public class WebSocketClient : MonoBehaviour {

    private WebSocket ws;
    void Start()
    {
        var t_url = "ws://localhost:" + ExampleWebSocketServer.port.ToString() + "/";
        Debug.Log(t_url);
        ws = new WebSocket(t_url);

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

        ws.OnMessage += (sender, e) =>
        {
            //    Debug.Log("WebSocket Message Type: " + e.Type + ", Data: " + e.Data);
            Debug.Log("WebSocket Message Type: " +e.GetType().ToString() + ", 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;
    }
}

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?