插件:Best HTTP

一、简介

官网文档

Best HTTP插件,官网文档:这款插件不但支持WebSockets,还支持HTTP,Sockets等通信方式是一款不错的插件。也支持打包Webgl。

将插件包拖入unity然后在代码里引入插件类,最后写代码

WebSocket/Socket与Tcp/Udp区别

http、https、websocket是在socket的基础上实现的应用层协议socket基于消息帧和TCP/IP协议更通用;由于这些应用层协议都是基于传输层的TPC/IP协议,因此都需要三次握手建立连接,所以消息传输具有可靠性;而对于传输层UPD协议实现的其它应用层协议NFS/SNMP/DNS/TFTP是无须握手无连接的,因此消息的传递不可靠;

二、WebSocket

绑定

代码

using UnityEngine;
using System;
using BestHTTP.WebSocket;
using System.Collections;
 
public class WebSocketClient : MonoBehaviour
{
    public string address = "ws://127.0.0.1:8002";

    WebSocket webSocket;
    private bool lockReconnect = false;
    private Coroutine _pingCor, _clientPing, _serverPing;

    private void Start()
    {
        CreateWebSocket();
    }

    private void Update()
    {
        Debug.Log(lockReconnect);
    }

    /*
     * 创建并初始化连接 start -------------------------------------------------------------------------------------------------------------------
     */
    void CreateWebSocket()
    {
        try
        {
            webSocket = new WebSocket(new Uri(address));
#if !UNITY_WEBGL
            webSocket.StartPingThread = true;
#endif
            InitHandle();
            webSocket.Open();
        }
        catch (Exception e)
        {
            Debug.Log("websocket连接异常:" + e.Message);
            ReConnect();
        }

    }
    void InitHandle()
    {
        RemoveHandle();
        webSocket.OnOpen += OnOpen;
        webSocket.OnMessage += OnMessageReceived;
        webSocket.OnClosed += OnClosed;
        webSocket.OnError += OnError;
    }
    void RemoveHandle()
    {
        webSocket.OnOpen -= OnOpen;
        webSocket.OnMessage -= OnMessageReceived;
        webSocket.OnClosed -= OnClosed;
        webSocket.OnError -= OnError;
    }
    void OnOpen(WebSocket ws)
    {
        Debug.Log("websocket连接成功");
        webSocket.Send("一个客户端连过来了");
        if (_pingCor != null)
        {
            StopCoroutine(_pingCor);
            _pingCor = null;
        }
        _pingCor = StartCoroutine(HeartPing());
        // 心跳检测重置
        HeartCheck();
    }
    void OnMessageReceived(WebSocket ws, string message)
    {
        // 如果获取到消息,心跳检测重置
        // 拿到任何消息都说明当前连接是正常的
        HeartCheck();
        Debug.Log(message);
    }
    void OnClosed(WebSocket ws, UInt16 code, string message)
    {
        Debug.LogFormat("OnClosed: code={0}, msg={1}", code, message);
        webSocket = null;
        ReConnect();
    }
    void OnError(WebSocket ws, string 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.LogFormat("OnError: error occured: {0}\n", (ex != null ? ex : "Unknown Error " + errorMsg));
        webSocket = null;
        ReConnect();
    }
    //end -------------------------------------------------------------------------------------------------------------------

    /*
     * 发送信息
     */
    public void WebSend(string msg)
    {
        if (webSocket == null || string.IsNullOrEmpty(msg)) return;
        if (webSocket.IsOpen)
        {
            webSocket.Send(msg);
        }
    }

    /*
     * 关闭连接
     */
    public void OnClose()
    {
        webSocket.Close(1000, "Bye!");
    }

    /*
     * 重新连接
     */
    void ReConnect()
    {
        if (this.lockReconnect)
            return;
        this.lockReconnect = true;
        StartCoroutine(SetReConnect());
    }
    private IEnumerator SetReConnect()
    {
        Debug.Log("正在重连websocket");
        yield return new WaitForSeconds(5);
        CreateWebSocket();
        lockReconnect = false;
    }

    /*
     * 心跳检测 start -------------------------------------------------------------------------------------------------------------------
     */

    private void HeartCheck()
    {
        if (_clientPing != null)
        {
            StopCoroutine(_clientPing);
            _clientPing = null;
        }
        if (_serverPing != null)
        {
            StopCoroutine(_serverPing);
            _serverPing = null;
        }
        _clientPing = StartCoroutine(ClientPing());
    }
    /*
     * 这里发送一个心跳,后端收到后,返回一个心跳消息
     * onmessage拿到返回的心跳就说明连接正常
     */
    private IEnumerator ClientPing()
    {
        yield return new WaitForSeconds(5);
        WebSend("heartbeat");
        _serverPing = StartCoroutine(ServerPing());
    }
    /*
     * 如果超过一定时间还没重置,说明后端主动断开了
     * 如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
     */
    private IEnumerator ServerPing()
    {
        yield return new WaitForSeconds(5);
        if (webSocket != null)
        {
            webSocket.Close();
        }

    }
    private IEnumerator HeartPing()
    {
        while (true)
        {
            yield return new WaitForSeconds(5);
            this.WebSend("Heartbeat");
        }
    }
    //end  -------------------------------------------------------------------------------------------------------------------
     


}

三、Http

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不努力谁会可怜你?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值