unity 连接需要联网的WebSocket
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
public class WebNetworkClient : SingletonManager<WebNetworkClient>
{
public string url = "ws://192.168.1.206:6070";
ClientWebSocket Socket;
CancellationToken ct;
public async void WebSocket()
{
try
{
Socket = new ClientWebSocket();
ct = new CancellationToken();
await Socket.ConnectAsync(new Uri(url), ct);
Debug.Log("开启雷达监听");
await Socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Token=" + UnityHttpHelper.Ins.api_token)), WebSocketMessageType.Text, true, ct);
while (true)
{
var result = new byte[10240];
await Socket.ReceiveAsync(new ArraySegment<byte>(result), ct);
ReceiveAsyncInfo(Encoding.UTF8.GetString(result, 0, result.Length));
}
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
void ReceiveAsyncInfo(string info)
{
}
private void OnApplicationQuit()
{
Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "拜拜", ct);
}
}