using System; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using DotRecast.Core.Collections; using Google.Protobuf; using Plugins.JNGame.Network; using Plugins.JNGame.Network.Action; using Plugins.JNGame.Network.Entity; using Plugins.JNGame.Network.Util; using TouchSocket.Core; using TouchSocket.Sockets; using UnityEngine; namespace JNGame.Network { public class JNTCPServer : JNServerBase { private TcpService service; private int _port; public int Port => _port; public override async Task OnInit() { service = new TcpService(); await service.SetupAsync( new TouchSocketConfig() .SetTcpDataHandlingAdapter(() => new FixedHeaderPackageAdapter()) ); service.Connecting = OnConnecting;//有客户端正在连接 service.Connected = OnConnected;//有客户端连接 service.Disconnected = OnDisconnected;//有客户端断开连接 service.Received = OnReceived;//客户端接收到消息 await service.StartAsync(_port = await GetPort());//启动 } /// /// 有客户端正在连接 /// /// /// private Task OnConnecting(SocketClient client, ConnectingEventArgs e) { Debug.Log($"[JNTCPServer] 有客户端正在连接"); return Task.CompletedTask; } /// /// 有客户端连接 /// /// /// /// /// private Task OnConnected(SocketClient client, ConnectedEventArgs e) { Debug.Log($"[JNTCPServer] 有客户端连接成功"); Dispatch((int)NActionEnum.LocalClientConnect,new JNServerParam() { Client = client.Id }); return Task.CompletedTask; } /// /// 有客户端断开连接 /// /// /// /// /// private Task OnDisconnected(SocketClient client, DisconnectEventArgs e) { Debug.Log($"[JNTCPServer] 有客户端断开连接"); Dispatch((int)NActionEnum.LocalClientDisconnect,new JNServerParam() { Client = client.Id }); return Task.CompletedTask; } /// /// 客户端接收到消息 /// /// /// /// /// private async Task OnReceived(SocketClient client, ReceivedDataEventArgs e) { byte[] data = new byte[e.ByteBlock.Len]; Array.Copy(e.ByteBlock.Buffer,data, data.Length); var param = NDataUtil.Parse(data); Dispatch(param.HId,new JNServerParam() { Client = client.Id, MessageID = param.ID, Message = param.Bytes, }); await UniTask.NextFrame(); } public override void OnClose() { base.OnClose(); service.Stop(); } protected virtual async UniTask GetPort() { await UniTask.NextFrame(); return 9001; } public void Send(SocketClient client,int hId,IMessage data = null) { Send(client.Id,hId,data); } public void Send(string client,int hId,IMessage data = null) { var bytes = NDataUtil.Encrypt(JNetParam.Build(this._id++, hId).SetData(data)); _byteSize[hId] = bytes.Length; service.SendAsync(client, bytes); } public void SendCallback(string client,int id,IMessage data = null) { var bytes = NDataUtil.Encrypt(JNetParam.Build(id, 0).SetData(data)); service.SendAsync(client, bytes); } public void AllSend(int hId,IMessage data = null) { service.GetClients().ForEach(client => { Send(client,hId,data); }); } } }