赞
踩
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); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。