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

传送门👈

相关推荐
BrightMZM9 小时前
记录一下Unity的BUG,Trial Version
unity·bug·打包·trial
杰瑞学AI10 小时前
我的全栈学习之旅:FastAPI (持续更新!!!)
后端·python·websocket·学习·http·restful·fastapi
▍ 小太阳 ☼11 小时前
Unity2022Navigation系统打开方式
unity·游戏引擎
qq_1702647515 小时前
unity升级对ab变更的影响
unity·游戏引擎
雪碧聊技术15 小时前
关于springboot定时任务和websocket的思考
websocket·springboot定时任务
ErizJ15 小时前
WebSocket | 一点简单了解
网络·websocket·网络协议
不伤欣17 小时前
Unity Mask镂空效果(常用于新手引导或高亮显示UI元素)
游戏·ui·unity·游戏引擎
qq_3266991117 小时前
Python解析Excel数据从入门到精通
websocket
一叶飘零_sweeeet1 天前
从轮询到实时推送:将站内消息接口改造为 WebSocket 服务
java·websocket
-快乐的程序员-2 天前
simple websocket用法
网络·websocket·网络协议