ご参考
手順1 [websocket-sharp.dll]をビルドする。
VisualStudio2019 でビルドするとエラーが出る。これはJsonsoftなど必要なライブラリがないため。
手順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;
}
}