2024-08-17 14:27:18 +08:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using BestHTTP.WebSocket;
|
|
|
|
|
using Cysharp.Threading.Tasks;
|
|
|
|
|
using DotRecast.Core.Collections;
|
|
|
|
|
using Google.Protobuf;
|
|
|
|
|
using Plugins.JNGame.Network.Entity;
|
|
|
|
|
using Plugins.JNGame.Network.Util;
|
|
|
|
|
using Plugins.JNGame.Util;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
|
|
namespace Plugins.JNGame.Network
|
|
|
|
|
{
|
|
|
|
|
public abstract class JNSocket : JNClientBase
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
private WebSocket _socket;
|
|
|
|
|
|
|
|
|
|
private UniTaskCompletionSource _onOpen;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public override async Task OnInit()
|
|
|
|
|
{
|
|
|
|
|
await StartConnect();
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-19 11:51:17 +08:00
|
|
|
|
public async Task StartConnect()
|
2024-08-17 14:27:18 +08:00
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
var url = $"{await this.GetUrl()}";
|
|
|
|
|
this._socket = new WebSocket(new Uri(url));
|
|
|
|
|
|
|
|
|
|
this._socket.OnOpen += OnOpen;
|
|
|
|
|
this._socket.OnMessage += OnMessageReceived;
|
|
|
|
|
this._socket.OnError += OnError;
|
|
|
|
|
this._socket.OnClosed += OnClosed;
|
|
|
|
|
this._socket.OnBinary += Onbinary;
|
|
|
|
|
|
|
|
|
|
Debug.Log($"[JNSocket]初始化WebSocket成功,URL:{url}");
|
|
|
|
|
this._socket.Open();
|
|
|
|
|
|
|
|
|
|
//等待连接成功
|
|
|
|
|
await (this._onOpen = new UniTaskCompletionSource()).Task;
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private void OnOpen(WebSocket websocket)
|
|
|
|
|
{
|
|
|
|
|
Debug.Log($"[JNSocket] OnOpen");
|
|
|
|
|
this._onOpen.TrySetResult();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnMessageReceived(WebSocket websocket, string message)
|
|
|
|
|
{
|
|
|
|
|
Debug.Log($"[JNSocket] OnMessageReceived");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnError(WebSocket websocket, string reason)
|
|
|
|
|
{
|
|
|
|
|
Debug.Log($"[JNSocket] OnError");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void OnClosed(WebSocket websocket, ushort code, string message)
|
|
|
|
|
{
|
|
|
|
|
Debug.Log($"[JNSocket] OnClosed");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void Onbinary(WebSocket websocket, byte[] data)
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
// NSystem.Log($"[JNSocket] Onbinary");
|
|
|
|
|
Dispatch(NDataUtil.Parse(data));
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected abstract UniTask<string> GetUrl();
|
|
|
|
|
|
|
|
|
|
public override void SendBytes(byte[] data)
|
|
|
|
|
{
|
|
|
|
|
_socket.Send(data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|