78 lines
2.1 KiB
C#
Raw Normal View History

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;
2024-08-22 20:37:39 +08:00
using TouchSocket.Core;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
2024-08-17 14:27:18 +08:00
using UnityEngine;
namespace Plugins.JNGame.Network
{
public abstract class JNSocket : JNClientBase
{
2024-08-22 20:37:39 +08:00
private WebSocketClient client;
2024-08-17 14:27:18 +08:00
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
{
2024-08-21 16:18:52 +08:00
2024-08-22 20:37:39 +08:00
client = new WebSocketClient();
2024-08-21 16:18:52 +08:00
2024-08-22 20:37:39 +08:00
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;
2024-08-21 16:18:52 +08:00
2024-08-22 20:37:39 +08:00
client.Connect();
Debug.Log($"[JNSocket]连接WebSocket成功");
2024-08-17 14:27:18 +08:00
}
2024-08-31 15:35:12 +08:00
public override void OnClose()
{
2024-09-13 04:06:25 +08:00
client?.Close();
client?.Dispose();
2024-08-31 15:35:12 +08:00
Debug.Log($"[JNTCPClient] 关闭对象");
base.OnClose();
}
2024-08-22 20:37:39 +08:00
private Task OnReceived(WebSocketClient webSocketClient, WSDataFrameEventArgs e)
2024-08-17 14:27:18 +08:00
{
2024-08-22 20:37:39 +08:00
if (e.DataFrame.Opcode == WSDataType.Binary && e.DataFrame.FIN)
{
Dispatch(NDataUtil.Parse(e.DataFrame.PayloadData));
}
return Task.CompletedTask;
2024-08-17 14:27:18 +08:00
}
protected abstract UniTask<string> GetUrl();
public override void SendBytes(byte[] data)
{
2024-08-22 20:37:39 +08:00
client.SendAsync(data);
2024-08-17 14:27:18 +08:00
}
}
}