Jason-c

Unity 连接ws,不用任何插件,忙活了一天终于搞定了,一直连接不上,原来是没有添加header,

代码比较简单,直接贴出来普度众生

 

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

public class NewBehaviourScript : MonoBehaviour
{
    private void Start()
    {
        WebSocket();
    }

    public async void WebSocket()
    {
        try
        {
            ClientWebSocket ws = new ClientWebSocket();
            CancellationToken ct = new CancellationToken();
            //添加header
            //ws.Options.SetRequestHeader("X-Token", "eyJhbGciOiJIUzI1N");
            Uri url = new Uri("ws://121.40.165.18:8800/v1/test/test");
            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);
        }
    }

}

  

分类:

技术点:

相关文章:

  • 2022-01-22
  • 2022-12-23
  • 2021-08-04
  • 2021-12-10
  • 2022-12-23
  • 2021-04-17
  • 2021-11-15
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案