🌼WebSocket-Server
🥪效果展示
在Unity中创建WebSocket服务器,从网页连接到该服务器进行消息通信,在Unity中接收到的消息都在主线程 中
🌭启动Server
直接运行Demo场景:Assets/ZYF/Tool/NetWork/WebSocket/Server/Demo/Demo.unity
csharp
using UnityEngine;
namespace ZYFWebSocket
{
public class ServerDemo : MonoBehaviour
{
private string webSocketServerUrl = "ws://127.0.0.1:8099";
private WebSocketServer server;
// Start is called before the first frame update
void Start()
{
this.server = webSocketServerUrl.StartWebSocket();
server.OnOpen(callback: (socket) =>
{
Debug.Log($"{nameof(WebSocketServer)} Open:{socket.ConnectionInfo.Id}");
socket.Send("连接成功~");
});
server.OnClose(callback: (socket) =>
{
Debug.Log($"{nameof(WebSocketServer)} Close:{socket.ConnectionInfo.Id}");
});
WebSocketExtension.onSocketErrorEvent.AddListener((data) =>
{
Debug.LogError($"{nameof(WebSocketServer)} Error:{data.socket.ConnectionInfo.Id}\n{data.error}");
});
WebSocketExtension.onSocketMessageEvent.AddListener((data) =>
{
Debug.Log($"{nameof(WebSocketServer)} msg:{data.socket.ConnectionInfo.Id}\n{data.msg}");
data.socket.Send("收到啦~");
});
}
private void OnDestroy()
{
this.server.Dispose();
}
}
}
🍱连接Server
Demo 演示由网页连接到Server,直接双击index文件启动页面即可:Assets/ZYF/Tool/NetWork/WebSocket/Server/Demo/index.html