using System; using System.Net; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; using Google.Protobuf; using Plugins.JNGame.Network.Entity; using TestNetty.Client.Initializers; using UnityEngine; using NotImplementedException = System.NotImplementedException; namespace Plugins.JNGame.Network { public class JNTCPClient : JNClientBase { private IChannel clientChannel; private IEventLoopGroup group; private Bootstrap bootstrap; public bool IsOpen => clientChannel is not null && clientChannel.Open; public override async Task OnInit() { await base.OnInit(); await StartConnect(); } public override async Task StartConnect() { if (!isStart) return; await CloseNetty(); group = new MultithreadEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel() .Option(ChannelOption.TcpNodelay, true) .Handler(new TcpClientInitializer(this)); try { if (bootstrap is not null) { Debug.Log($"[JNTCPClient] 开始连接"); clientChannel = await bootstrap.ConnectAsync( await GetEndPoint() ); Debug.Log($"[JNTCPClient] 连接成功"); } } catch (Exception e) { Debug.LogWarning(e.Message); Debug.Log($"[JNTCPClient] 连接失败 1s后重试"); await UniTask.DelayFrame(1000); await StartConnect(); } } protected virtual async UniTask GetEndPoint() { await UniTask.NextFrame(); return new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001); } public override void OnClose() { base.OnClose(); CloseNetty(); } private async Task CloseNetty() { clientChannel?.CloseAsync(); if (group is not null) await group.ShutdownGracefullyAsync(); group = null; clientChannel = null; bootstrap = null; } public override void Send(int hId, IMessage data = null) { base.Send(hId, data); if (IsOpen) { // clientChannel?.WriteAndFlushAsync(JNetParam.Build(this._id++, hId).SetData(data)); } } } }