zoukankan      html  css  js  c++  java
  • Unity中实现WebSocket客户端

    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);
            }
        }
    
    }
    
  • 相关阅读:
    Asp.net操作Excel----NPOI
    Python第一模块
    Sping笔记一览
    IO流技术一览
    事务技术一览
    日常问题记录
    分页与JDBC显示文档。
    分页技术与JDBC一览
    JDBC 技术开发
    MYSQL
  • 原文地址:https://www.cnblogs.com/ezhar/p/14328681.html
Copyright © 2011-2022 走看看