Unity WebSocket-Server

🌼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

传送门👈

相关推荐
淡海水4 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景4 小时前
4.6 显存和缓存
unity
aesthetician5 小时前
实时通信的艺术:Server-Sent Events (SSE) 与 WebSocket 的深度解析
网络·websocket·网络协议
CaracalTiger5 小时前
OpenClaw-VSCode:在 VS Code 中通过 WebSocket 远程管理 OpenClaw 网关的完整方案
运维·ide·人工智能·vscode·websocket·开源·编辑器
Zik----6 小时前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景17 小时前
4.5 顶点和片元
unity
默默前行的虫虫19 小时前
解决EMQX WebSocket连接不稳定及优化WS配置提升稳定性?
websocket
闲人编程1 天前
使用FastAPI和WebSocket构建高性能实时聊天系统
websocket·网络协议·网络编程·fastapi·持久化·实时聊天·codecapsule
在路上看风景1 天前
31. Unity 异步加载的底层细节
unity
天人合一peng1 天前
Unity中做表头时像work中整个调整宽窄
unity