Unity3D WebGL平台使用WebSocket通信的方法和示例

      之前在WebGL平台和服务端交互的时候使用的是UnityWebRequest,通过WebAPI的方式进行交互,后来发现可以用websocket交互后就果断换了WebSocket。

一、Unity3D客户端

我在Unity端使用的是NativeWebSocket

NativeWebSocket下载地址

直接导入Unity即可,

下面是适配的代码,直接挂载在GameObject。

 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using NativeWebSocket;
using LitJson;

public class Connection : MonoBehaviour
{
    WebSocket websocket;

    public Text textLog;


    async void Start()
    {
        websocket = new WebSocket("ws://127.0.0.1:7181");

        websocket.OnOpen += () =>
        {
            Debug.Log("Connection open!");
            // textLog.text = $"Connection open! {Time.realtimeSinceStartup} \n {textLog.text}";
        };

        websocket.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
            // textLog.text = $"Error:{e} {Time.realtimeSinceStartup} \n {textLog.text}";
        };

        websocket.OnClose += (e) =>
        {
            Debug.Log("Connection closed!");
            // textLog.text = $"Connection closed! {Time.realtimeSinceStartup} \n {textLog.text}";
        };

        websocket.OnMessage += (bytes) =>
        {
            // Debug.Log("OnMessage!");
             //textLog.text = $"OnMessage! {Time.realtimeSinceStartup} \n {textLog.text}";
            //  Debug.Log(bytes);

            // getting the message as a string
            var message = System.Text.Encoding.Default.GetString(bytes);
            textLog.text = $"消息内容:{message} ";
            Debug.Log("OnMessage! " + message);

            //SocketData Sdata= JsonMapper.ToObject<SocketData>(message);
            var Sdata=JsonMapper.ToObject< Dictionary<string, string>>(message);
            Debug.Log(Sdata["data"]);
            string b = Sdata["data"];
           byte[] bs= Convert.FromBase64String(b);
            var m = System.Text.Encoding.Default.GetString(bs);
            Debug.Log(m);
        };

        // Keep sending messages at every 0.3s
       // InvokeRepeating("SendWebSocketMessage", 0.0f, 2f);

        // waiting for messages
        await websocket.Connect();
    }

    void Update()
    {
#if !UNITY_WEBGL || UNITY_EDITOR
        websocket.DispatchMessageQueue();
#endif
    }

    async void SendWebSocketMessage()
    {
        if (websocket.State == WebSocketState.Open)
        {
            // Sending bytes
            await websocket.Send(new byte[] { 10, 20, 30 });

            // Sending plain text
            await websocket.SendText("plain text message");
        }
    }
    
    private async void OnApplicationQuit()
    {
        await websocket.Close();
    }




}


二、服务端

运行后可与客户端交互

下载地址

 

转载请说明出处内容投诉
CSS教程_站长资源网 » Unity3D WebGL平台使用WebSocket通信的方法和示例

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买