using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using JNGame.Util; using Plugins.JNGame.Network.Util; using UnityEngine; using NotImplementedException = System.NotImplementedException; namespace Plugins.JNGame.Network { public abstract class JNTCPClient1 : JNClientBase { /// /// 客户端 /// /// private Socket client; /// /// 客户端线程 /// /// private Thread thread; /// /// 是否连接 /// public bool isConnect { get; private set; } private Queue cache = new (); public override async Task OnInit() { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(await GetEndPoint()); thread = new Thread(CreatConnectSocket); thread.Start(); } public override void OnClose() { Debug.Log($"[JNTCPClient] 关闭客户端"); base.OnClose(); client?.Close(); thread?.Abort(); } protected virtual async UniTask GetEndPoint() { await UniTask.NextFrame(); return new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001); } private void CreatConnectSocket() { Debug.Log($"[JNTCPClient] 连接服务器成功"); isConnect = true; PushCache(); byte[] bytes = new byte[102400]; try { while (true) { var max = client.Receive(bytes); var message = new byte[max]; Array.Copy(bytes, message, max); var param = NDataUtil.Parse(message); Dispatch(param); } } catch (Exception e) { // ignored Debug.LogWarning(e.Message); Debug.Log($"[JNTCPClient] 断开连接"); isConnect = false; client.Close(); } } public override void SendBytes(byte[] data) { if (data is null || data.Length <= 0) return; cache.Enqueue(data); if (isConnect) { PushCache(); } } /// /// 发送缓存 /// public void PushCache() { while (isConnect && cache.TryDequeue(out var bytes)) { NetTool.SendAsync(client,bytes); } } } }