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

传送门👈

相关推荐
dangoxiba3 小时前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
拾伍廿肆5 小时前
python - websocket
python·websocket·django
Sun_Sherry11 小时前
FastAPI: websocket的用法及举例
websocket·网络协议·fastapi
先生沉默先20 小时前
使用Materialize制作unity的贴图,Materialize的简单教程,Materialize学习日志
学习·unity·贴图
貂蝉空大20 小时前
uni-app 封装websocket 心跳检测,开箱即用
websocket·网络协议·uni-app
十画_8241 天前
Visual Studio 小技巧记录
unity·visual studio
red_redemption1 天前
cpp,git,unity学习
git·unity·游戏引擎
tealcwu1 天前
【Unity踩坑】Unity更新Google Play结算库
unity·游戏引擎
先生沉默先1 天前
unity 默认渲染管线材质球的材质通道,材质球的材质通道
unity·游戏引擎·材质
白鹭float.1 天前
【Unity AI】基于 WebSocket 和 讯飞星火大模型
人工智能·websocket·unity