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

传送门👈

相关推荐
拾忆丶夜1 小时前
unity webgl 阴影条纹问题
unity·游戏引擎·webgl
TickDB2 小时前
美股行情 API 接入避坑:REST 快照、WebSocket 推送、盘前盘后数据的边界
人工智能·python·websocket·行情数据 api
tealcwu11 小时前
【Unity实战】Unity IAP 4.x 在 Windows Store (UWP) 平台上的实现指南
windows·unity·游戏引擎
玉夏11 小时前
【Shader基础】CG/HLSL 基础语法
unity·shader
垂葛酒肝汤14 小时前
Unity的UGUI的坐标
unity
winlife_14 小时前
让 AI 写敌人状态机,并用脚本化场景验证状态转换正确:funplay-unity-mcp 实战
人工智能·unity·游戏引擎·ai编程·状态机·mcp
tealcwu14 小时前
【Unity实战】Unity IAP 5.3 中实现 Windows Custom Store 实战教程
windows·unity·游戏引擎
unityのkiven14 小时前
工作分享1(26.5.27):基于栈实现全局返回逻辑通用架构设计(适配异步 + 确认弹窗)
游戏·unity·c#·客户端架构
Wonderful U16 小时前
基于 Django Channels 与 WebSocket 的实时聊天室:群聊、私聊、离线消息与持久化存储全实现
python·websocket·django
shuxiaohua16 小时前
一次现网问题定位-websocket断连问题
网络·websocket·网络协议