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;
//SingletonManager: 继承MonoBehaviour的单例(也可以直接继承MonoBehaviour)
public class WebNetworkClient : SingletonManager<WebNetworkClient>
{
//服务器的地址
public string url = "ws://192.168.1.206:6070";
ClientWebSocket Socket;
CancellationToken ct;
//启动WebSocket(有需要在其他脚本启动/可以增加一个Awake在这个脚本调用)
public async void WebSocket()
{
try
{
Socket = new ClientWebSocket();
ct = new CancellationToken();
//添加header
//Socket.Options.SetRequestHeader("Authorization", token);
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)
{
//收到服务器返回的数据
//Debug.Log(info);
}
private void OnApplicationQuit()
{
//应用关闭 主动断开链接
Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "拜拜", ct);
}
}
文章来源地址https://www.toymoban.com/news/detail-543234.html
文章来源:https://www.toymoban.com/news/detail-543234.html
到了这里,关于unity 连接WebSocket的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!