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);
        }
    }

}

相关文章:

  • 2021-06-17
  • 2022-12-23
  • 2021-10-30
  • 2021-11-03
  • 2021-11-27
  • 2021-07-25
  • 2022-12-23
猜你喜欢
  • 2022-01-05
  • 2022-01-05
  • 2022-12-23
  • 2022-02-12
  • 2022-01-08
  • 2022-12-23
相关资源
相似解决方案