DESKTOP-5RP3AKU\Jisol ced7fdce74 完美
2024-09-13 04:06:25 +08:00

78 lines
2.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 TouchSocket.Core;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
using UnityEngine;
namespace Plugins.JNGame.Network
{
public abstract class JNSocket : JNClientBase
{
private WebSocketClient client;
public override async Task OnInit()
{
await StartConnect();
}
public async Task StartConnect()
{
client = new WebSocketClient();
await client.SetupAsync(new TouchSocketConfig()
.SetRemoteIPHost(await this.GetUrl())
.ConfigurePlugins(a =>
{
a.UseReconnection(-1, true, 1000); //如需永远尝试连接tryCount设置为-1即可。
})
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
}));
client.Received += OnReceived;
client.Connect();
Debug.Log($"[JNSocket]连接WebSocket成功");
}
public override void OnClose()
{
client?.Close();
client?.Dispose();
Debug.Log($"[JNTCPClient] 关闭对象");
base.OnClose();
}
private Task OnReceived(WebSocketClient webSocketClient, WSDataFrameEventArgs e)
{
if (e.DataFrame.Opcode == WSDataType.Binary && e.DataFrame.FIN)
{
Dispatch(NDataUtil.Parse(e.DataFrame.PayloadData));
}
return Task.CompletedTask;
}
protected abstract UniTask<string> GetUrl();
public override void SendBytes(byte[] data)
{
client.SendAsync(data);
}
}
}