拷贝即用(加个你自己的userID):
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class ConnetWebSocket : MonoBehaviour
{
private ClientWebSocket ws;
private void Start()
{
WebSocket();
}
public async void WebSocket()
{
try
{
ws = new ClientWebSocket();
CancellationToken ct = new CancellationToken();
Uri url = new Uri("ws://127.0.0.1:9999/test/websocket/" + {your userID});
await ws.ConnectAsync(url, 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("web conection receive : " + str);
ReceiveDataModel receiveData = JsonUtility.FromJson<ReceiveDataModel>(str);
if (receiveData.msgId == 1001)
{
Debug.Log("收到指令...");
//do...
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void OnDestroy()
{
if(ws != null) ws.Dispose();
}
}
[SerializeField]
public class ReceiveDataModel
{
public int msgId;
public string content;
}