Unity WebGL用到的WebSocket

WebGL与服务器交互总结(资源及代码)想到啥写啥

首先用到的资源BestHttp:
传送门

我这里只做了客户端,服务端是同事做的。同样是用的WebSocket,具体是什么框架就不得而知。这里只介绍客户端:

using BestHTTP.WebSocket;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;


public class WebSocketClient : Singleton<WebSocketClient>
{
    #region Socket
    private WebSocket webSocket;
    private string url;
    #endregion


    public void Init(string uri = null)
    {
		webSocket = new WebSocket(new Uri(url));
        webSocket.OnOpen += OnOpen;
        webSocket.OnMessage += OnMessageReceived;
        webSocket.OnError += OnError;
        webSocket.OnClosed += OnClosed;
    }

    private void antiInit()
    {
        webSocket.OnOpen = null;
        webSocket.OnMessage = null;
        webSocket.OnError = null;
        webSocket.OnClosed = null;
        webSocket = null;
    }

    public void Connect()
    {
       webSocket.Open();
    }

    public void Send(string msg)
    {
       webSocket.Send(msg);
    }
    
    public void Close()
    {
        webSocket.Close();
    }

    #region WebSocket Event Handlers

    /// 
    /// Called when the web socket is open, and we are ready to send and receive data
    /// 
    void OnOpen(WebSocket ws)
    {
        Debug.Log("connected");
    }

    /// 
    /// Called when we received a text message from the server
    /// 
    void OnMessageReceived(WebSocket ws, string message)
    {
        Debug.Log(message);
    }

    /// 
    /// Called when the web socket closed
    /// 
    void OnClosed(WebSocket ws, UInt16 code, string message)
    {
        Debug.Log(message);
        antiInit();
        Init();
    }

    /// 
    /// Called when an error occured on client side
    /// 
    void OnError(WebSocket ws, Exception ex)
    {
        string errorMsg = string.Empty;
#if !UNITY_WEBGL || UNITY_EDITOR
        if (ws.InternalRequest.Response != null)
            errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
#endif
        Debug.Log(errorMsg);
        antiInit();
        Init();
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsOpen)
        {
            webSocket.Close();
            antiInit();
        }
    }
    #endregion
}

上面这些就是一个最简单最完整的客户端:Init()初始化,Connect()连接,Send(string msg)发送消息,OnMessageReceived(WebSocket ws, string message)接收消息。具体的逻辑就自己处理喽。

WebGL只能使用WebSocket来进行网络通信,其他的都不支持,且但凡是用到System.Net这个命名空间的也不能使用

你可能感兴趣的:(工具,网络,websocket)