最近考虑到项目中如果监听一个设备信息的话,需要持续的监听,如果用unity一直请求的话会很消耗性能,所以在网上搜了一下,发现这种需求叫推送服务,在网上找到好多说用插件的,但是我不想用插件,然后找到了一段代码,直接使用c#自带的websocket,因为没有测试环境,所以没有测试,记录下来以供后续使用。 代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class WebSocketManager : MonoBehaviour
{
private WebSocket webSocket;
private void Start()
{
StartWebSocket();
}
private async void StartWebSocket()
{
try
{
ClientWebSocket ws = new ClientWebSocket();
CancellationToken ct = new CancellationToken();
Uri uri = new Uri("aaaaaa");
await ws.ConnectAsync(uri, 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 e)
{
Debug.LogError(e);
}
}
}
|