ClientWebSocket

作者:追风剑情 发布于:2019-11-13 14:34 分类:C#

参考 https://www.cnblogs.com/Jason-c/p/11117002.html
https://segmentfault.com/a/1190000014582485?utm_source=tag-newest
微软官方文档 ClientWebSocket类

WebSocket客户端,用来发送或接收WebSocket消息。如果你的服务所在的域是HTTPS的,那么使用的WebSocket协议也必须是wss而不是ws

示例:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading;
using System.Text;
using UnityEngine;

/// <summary>
/// 封装WebSocket
/// </summary>
public class WebSocketWrap
{
    //连接状态改变
    public Action<WebSocketState> OnWebSocketState;
    //连接失败
    public Action OnConnectError;
    //数据返回
    public Action<string> OnMessage;

    private ClientWebSocket ws;
    private CancellationToken ct;

    //uri: 例如 ws://192.168.1.155:8800
    public async void Connect(string uri)
    {
        try
        {
            Debug.LogFormat("[WebSocket] 开始连接 {0}", uri);
            ws = new ClientWebSocket();
            ct = new CancellationToken();
            Uri url = new Uri(uri);
            await ws.ConnectAsync(url, ct);

            if (OnWebSocketState != null)
                OnWebSocketState(ws.State);

            while (true)
            {
                var result = new byte[1024];
                await ws.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
                var str = Encoding.UTF8.GetString(result, 0, result.Length);

                if (OnMessage != null)
                    OnMessage(str);
            }
        }
        catch(Exception ex)
        {
            Debug.LogErrorFormat("[WebSocket] {0}\nCloseStatus: {1}\nCloseStatusDescription: {2}", ex.Message, ws.CloseStatus, ws.CloseStatusDescription);
            if (OnConnectError != null)
                OnConnectError();
        }
        finally
        {
            if (ws != null)
                ws.Dispose();
            ws = null;
        }
    }

    // 发送心跳
    public void SendHeartBeat()
    {
        if (ws == null || ws.State != WebSocketState.Open)
            return;

        ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("{\"id\":101}")), WebSocketMessageType.Text, true, ct);
    }

    // 发送数据
    public void Send(int id, string data)
    {
        if (ws == null || ws.State != WebSocketState.Open)
        {
            Debug.LogErrorFormat("[WebSocket] 发送数据失败,未连接上服务器。");
            return;
        }

        WebDataStructure wds = new WebDataStructure();
        wds.id = id;
        wds.data = data;
        string json = JsonUtility.ToJson(wds);
        ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(json)), WebSocketMessageType.Text, true, ct);
    }

    //中止WebSocket连接并取消任何挂起的IO操作
    public void Abort()
    {
        if (ws == null)
            return;
        ws.Abort();
    }
}



public class WebDataStructure
{
    public int id;
    public string data; //json串
}


标签: C#

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号