Unity中实现WebSocket客户端

时间:2021-01-26 10:41:10   收藏:0   阅读:148
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using UnityEngine;
 
/*by Alexander*/

public class WebSocketRequester: MonoBehaviour
{
    private void Start()
    {
        SendWebSocketRequest();
    }

    public async void SendWebSocketRequest()
    {
        try
        {
            ClientWebSocket ws = new ClientWebSocket();
            CancellationToken ct = new CancellationToken();
            // add header
            //ws.Options.SetRequestHeader("X-Token", "eyJhbGciOiJIUzI1N");
            Uri url = new Uri(ServerURL.wssUrl);
            await ws.ConnectAsync(url, ct);
            await ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("hello")), WebSocketMessageType.Binary, true, ct); 
            //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);
                Debug.Log(str);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

}

原文:https://www.cnblogs.com/ezhar/p/14328681.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!