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

传送门👈

相关推荐
Thomas_YXQ14 小时前
Unity3D编辑器扩展-物体批量替换设置材质
游戏·unity·编辑器·游戏引擎·材质
雪下的新火17 小时前
Unity-HDRP场景搭建-那山
经验分享·笔记·unity·游戏引擎·场景搭建
郝学胜-神的一滴1 天前
深度解析游戏引擎中的相机:视图矩阵
程序人生·unity·矩阵·游戏引擎·godot·图形渲染·虚幻
四岁爱上了她2 天前
vue3+socketio一个即时通讯的小demo
vue.js·websocket
谷宇.2 天前
【Unity3D实例-功能-拔枪】角色拔枪(三)IK的使用-紧握武器
游戏·unity·c#·unity3d·游戏开发·游戏编程·steam
SmalBox2 天前
【渲染流水线】[逐片元阶段]-[模版测试]以UnityURP为例
unity·渲染
小蜗 strong2 天前
unity中实现机械臂自主运动
unity·游戏引擎
★YUI★3 天前
学习游戏制作记录(制作系统与物品掉落系统)8.16
学习·游戏·ui·unity·c#
还听珊瑚海吗3 天前
基于WebSocket和SpringBoot聊天项目ChatterBox测试报告
spring boot·websocket·网络协议
SmalBox3 天前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
unity·渲染