mirror of
https://gitee.com/jisol/jisol-game/
synced 2025-06-26 03:14:47 +00:00
88 lines
2.2 KiB
C#
88 lines
2.2 KiB
C#
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();
|
||
}
|
||
|
||
public async Task StartConnect()
|
||
{
|
||
|
||
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);
|
||
}
|
||
|
||
}
|
||
}
|