From 9e1e0707dc060dcb12570fe15e0eabd8feb7bf5f Mon Sep 17 00:00:00 2001 From: lishuo Date: Tue, 1 Aug 2023 10:55:45 +0800 Subject: [PATCH] feature:3.0.0 --- OnlineUserPool.csproj | 4 - Services/TcpService.cs | 221 ++++++++++++++++++++++-------- Services/TcpService1.cs | 213 ---------------------------- ViewModels/MainWindowViewModel.cs | 51 +++---- 4 files changed, 180 insertions(+), 309 deletions(-) delete mode 100644 Services/TcpService1.cs diff --git a/OnlineUserPool.csproj b/OnlineUserPool.csproj index 55c0642..3084aa6 100644 --- a/OnlineUserPool.csproj +++ b/OnlineUserPool.csproj @@ -5,10 +5,6 @@ netcoreapp3.1 true - - - - diff --git a/Services/TcpService.cs b/Services/TcpService.cs index 5c94e75..516e36f 100644 --- a/Services/TcpService.cs +++ b/Services/TcpService.cs @@ -1,93 +1,198 @@ -using OnlineUserPool.Model; +using NetCoreServer; +using Newtonsoft.Json; +using OnlineUserPool.Model; using OnlineUserPool.Unility; using Serilog; -using SimpleTcp; using System; -using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; -using System.Threading.Tasks; namespace OnlineUserPool.Services { public class TcpService : IService { - private bool _stop = false; - SimpleTcpServer socket; - Action _action; + private PfTcpServer _server; - public void RunServer(Action action) + public void Close() { - //throw new NotImplementedException(); - - _action = action; - //var ip = IPAddress.Parse("192.168.0.97"); - var b = IPAddress.Any; - socket = new SimpleTcpServer($"{ IPAddress.Any }:11001"); - socket.Events.ClientConnected += Events_ClientConnected; - socket.Events.ClientDisconnected += Events_ClientDisconnected; - socket.Events.DataReceived += Events_DataReceived; - - Task.Run(() => - { - socket.Start(); - }); + } - private void Events_DataReceived(object sender, SimpleTcp.DataReceivedEventArgs e) + public void RunServer(Action action, Action disconnected = null) { - var returnData = Encoding.UTF8.GetString(e.Data); - Debug.WriteLine(returnData); + _server = new PfTcpServer(IPAddress.Any, ConfigHelp.TcpPort, (ip, model) => { action(ip, model, this); }, + disconnected); - foreach (var item in returnData.Split(new string[] { "}" }, StringSplitOptions.RemoveEmptyEntries)) - { - var msg = Newtonsoft.Json.JsonConvert.DeserializeObject(item +"}"); - var ipEndPoint = IPEndPoint.Parse(e.IpPort); - _action(ipEndPoint, msg, this); - } - } - - private void Events_ClientDisconnected(object sender, ClientDisconnectedEventArgs e) - { - - } - - private void Events_ClientConnected(object sender, ClientConnectedEventArgs e) - { - Debug.WriteLine("有新客户端连接" + e.IpPort); + _server.Start(); } public void Send(byte[] dgram, int bytes, IPEndPoint endPoint) { - if(dgram == null || !dgram.Any()) + if (dgram == null || !dgram.Any()) { return; } - foreach (var item in socket.GetClients()) + var session = _server.FindSession(endPoint); + if (session is { IsConnected: true }) { - //try - //{ - if(socket.IsConnected(item) == false) - { - continue; - } - socket.Send(item, dgram); - //} - //catch(Exception e) - //{ - // Log.Error($"{ item.ToString() }:{ e.Message }\r\n{ e.StackTrace }"); - //} + session.SendAsync(dgram); } } - public void Close() + private class PfTcpServer : TcpServer { - _stop = true; - socket.Dispose(); + private Action _action; + private Action _disconnected; + + public PfTcpServer(IPAddress address, int port, Action action, + Action disconnected = null) : base(address, port) + { + _action = action; + _disconnected = disconnected; + } + + protected override TcpSession CreateSession() + { + return new PfTcpSession(this, _action); + } + + protected override void OnError(SocketError error) + { + //base.OnError(error); + Debug.WriteLine(error); + } + + public TcpSession FindSession(IPEndPoint ip) + { + try + { + var item = this.Sessions.Values.FirstOrDefault(t => + t.Socket.Connected && t.Socket.RemoteEndPoint.ToString() == ip.ToString()); + return item; + } + catch (Exception e) + { + Log.Error( $"Fail to FindSession:{e}"); + return null; + } + } + + protected override void OnDisconnected(TcpSession session) + { + var currentSession = (session as PfTcpSession); + if (currentSession?.IPEndPoint != null) + { + _disconnected?.Invoke(currentSession.IPEndPoint); + } + + base.OnDisconnected(session); + } + } + + private class PfTcpSession : TcpSession + { + Action _action; + public IPEndPoint IPEndPoint { get; private set; } + + public PfTcpSession(TcpServer server, Action action) : base(server) + { + _action = action; + } + + protected override void OnConnected() + { + base.OnConnected(); + Debug.WriteLine("有新的Tcp连接"); + IPEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString()); + } + + protected override void OnDisconnected() + { + base.OnDisconnected(); + Debug.WriteLine("Tcp断开连接"); + } + + private readonly StringBuilder _dataBuffer = new StringBuilder(); + + protected override void OnReceived(byte[] buffer, long offset, long size) + { + var data = string.Empty; + try + { + data = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); + foreach (var item in data) + { + this._dataBuffer.Append(item); + if (item != '}') continue; + Debug.WriteLine("收到消息:" + this._dataBuffer); + + var msg = JsonConvert.DeserializeObject(this._dataBuffer.ToString()); + var ipEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString()); + switch (msg.CommandType) + { + case 1: + _action(ipEndPoint, JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 2: + _action(ipEndPoint, JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 3: + switch (msg.SubType) + { + case 0: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 1: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 2: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 3: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 4: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 5: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + case 6: + _action(ipEndPoint, + JsonConvert.DeserializeObject(this._dataBuffer.ToString())); + break; + } + + break; + default: + _action(ipEndPoint, msg); + break; + } + + this._dataBuffer.Clear(); + } + } + catch (Exception ex) + { + Log.Error($"接受到的数据处理时出错:{data}\r\n{ex.Message}\r\n{ex.StackTrace}"); + } + } + + protected override void OnError(SocketError error) + { + //base.OnError(error); + Debug.WriteLine(error); + } } } } diff --git a/Services/TcpService1.cs b/Services/TcpService1.cs deleted file mode 100644 index 375cc49..0000000 --- a/Services/TcpService1.cs +++ /dev/null @@ -1,213 +0,0 @@ -using NetCoreServer; -using Newtonsoft.Json; -using OnlineUserPool.Model; -using OnlineUserPool.Unility; -using Serilog; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text; - -namespace OnlineUserPool.Services -{ - public class TcpService1 : IService - { - private PfTcpServer _server; - - public void Close() - { - //throw new NotImplementedException(); - } - - public void RunServer(Action action, Action disconnected = null) - { - //throw new NotImplementedException(); - //_action = action; - _server = new PfTcpServer(IPAddress.Any, ConfigHelp.TcpPort, (ip, model)=> { - action(ip, model, this); - }, disconnected); - //_server.OptionNoDelay = true; - _server.Start(); - } - - public void Send(byte[] dgram, int bytes, IPEndPoint endPoint) - { - if (dgram == null || !dgram.Any()) - { - return; - } - //_server.Multicast(dgram); - var session = _server.FindSession(endPoint); - if(session != null && session.IsConnected) - { - session.SendAsync(dgram); - } - } - - class PfTcpServer : TcpServer - { - private Action _action; - private Action _disconnected; - //private System.Collections.Generic.Dictionary clients = new Dictionary(); - public PfTcpServer(IPAddress address, int port, Action action, Action disconnected = null) :base(address, port) - { - _action = action; - _disconnected = disconnected; - } - - protected override TcpSession CreateSession() - { - //return base.CreateSession() - return new PfTcpSession(this, _action); - } - - protected override void OnError(SocketError error) - { - //base.OnError(error); - Debug.WriteLine(error); - } - - public TcpSession FindSession(IPEndPoint ip) - { - var item = this.Sessions.Values.FirstOrDefault(t => t.Socket.RemoteEndPoint.ToString() == ip.ToString()); - return item; - } - - protected override void OnDisconnected(TcpSession session) - { - //var bbb = this.Sessions.GetValueOrDefault(session.Id); - - var bbb = (session as PfTcpSession); - if(bbb.IPEndPoint != null) - { - _disconnected?.Invoke(bbb.IPEndPoint); - } - base.OnDisconnected(session); - } - } - - class PfTcpSession : TcpSession - { - Action _action; - public IPEndPoint IPEndPoint { get; private set; } - public PfTcpSession(TcpServer server, Action action) : base(server) { - _action = action; - - } - - protected override void OnConnected() - { - base.OnConnected(); - Debug.WriteLine("有新的Tcp连接"); - - IPEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString()); - } - - protected override void OnDisconnected() - { - base.OnDisconnected(); - Debug.WriteLine("Tcp断开连接"); - } - private string temp = ""; - protected override void OnReceived(byte[] buffer, long offset, long size) - { - //base.OnReceived(buffer, offset, size); - - //Debug.WriteLine(returnData); - //Log.Information(returnData + "\r\n"); - string returnData = ""; - try - { - returnData = Encoding.UTF8.GetString(buffer, (int)offset, (int)size); - //var msg = Newtonsoft.Json.JsonConvert.DeserializeObject(returnData); - //var ipEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString()); - //_action(ipEndPoint, msg); - foreach (var item in returnData) - { - if(item == '}') - { - temp += item; - Debug.WriteLine("收到消息:"+temp); - var msg = JsonConvert.DeserializeObject(temp); - var ipEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString()); - if (msg.CommandType == 1) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - else if (msg.CommandType == 2) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - //else if(msg.CommandType == 3) - //{ - // _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - //} - else if (msg.CommandType == 3) - { - if (msg.SubType == 0) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - if (msg.SubType == 1) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - if (msg.SubType == 2) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - if (msg.SubType == 3) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - - if (msg.SubType == 4) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - if (msg.SubType == 5) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - if (msg.SubType == 6) - { - _action(ipEndPoint, JsonConvert.DeserializeObject(temp)); - } - } - else - { - _action(ipEndPoint, msg); - } - temp = ""; - } - else - { - temp += item; - } - } - - //foreach (var item in returnData.Split(new string[] { "}" }, StringSplitOptions.RemoveEmptyEntries)) - //{ - // //if (string.IsNullOrWhiteSpace(item)) continue; - // var msg = Newtonsoft.Json.JsonConvert.DeserializeObject(item + "}"); - // var ipEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString()); - // _action(ipEndPoint, msg); - //} - } - catch (Exception ex) - { - Log.Error($"接受到的数据处理时出错:{ returnData }\r\n{ ex.Message }\r\n{ ex.StackTrace }"); - } - } - - protected override void OnError(SocketError error) - { - //base.OnError(error); - Debug.WriteLine(error); - } - } - } -} diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index d72889d..a927b6f 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -104,7 +104,7 @@ namespace OnlineUserPool.ViewModels //mapRecordRankingHander = new MultiUserHandle(); Log.Information($"初始化连接,当前地址:{ IPAddress.Any }:{ConfigHelp.UdpPort}"); - new TcpService1().RunServer(ReceivedData, CientDisconnected); + new TcpService().RunServer(ReceivedData, CientDisconnected); //var tet = new System.Collections.Concurrent.ConcurrentBag(); var _udpService = new UdpService(); @@ -302,7 +302,7 @@ namespace OnlineUserPool.ViewModels var G = $"{total}l[{gameRoom},detail{{{ss}}}]"; var temp = string.Join("|", list.Select(m => m.ToString(2))) + "|"; var strV21 = $"*l{{{ temp }}};g{{{ G}}};#"; - var ddd = new Data1(strV21); + var ddd = new NetworkData(strV21); var needList = Clients.Where(c => c.RoomId == gameRoom.RoomId).ToList(); foreach (var client in needList) @@ -329,7 +329,7 @@ namespace OnlineUserPool.ViewModels { var G = GameRoomMessageHandler(item); var strV21 = $"*l{{{ temp }}};g{{{G}}};#"; - var ddd = new Data1(strV21); + var ddd = new NetworkData(strV21); bool isZip = item.Encoding == "gzip"; item.Service.Send(ddd.GetBytes(isZip), ddd.GetBytes(isZip).Length, item.IPEndPoint); } @@ -382,7 +382,7 @@ namespace OnlineUserPool.ViewModels } var strV21 = $"*l{{{ temp }}};g{{{roomInfo}}};#"; - var ddd = new Data1(strV21); + var ddd = new NetworkData(strV21); bool isZip = needSend.Encoding == "gzip"; needSend.Service.Send(ddd.GetBytes(isZip), ddd.GetBytes(isZip).Length, needSend.IPEndPoint); } @@ -749,7 +749,8 @@ namespace OnlineUserPool.ViewModels item.EndDistance = Math.Round(item.EndDistance, 5); item.WeightKg = Math.Round(item.WeightKg, 2); } - string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list.Select(m => new { + + var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list.Select(m => new { m.RouteId, m.MemberId, m.Point, @@ -765,7 +766,6 @@ namespace OnlineUserPool.ViewModels m.FrameRate, })); var data = Encoding.ASCII.GetBytes(jsonString); - //SendDataSize = (data.Length/1000D).ToString() +"KB"; var strV1 = string.Join("|", list.Select(m => m.ToString(1))); if (!string.IsNullOrWhiteSpace(strV1)) @@ -773,24 +773,11 @@ namespace OnlineUserPool.ViewModels strV1 += "|"; } - - //strV1 = "abcdefghijklmnopqrstuvwxyz"; - //System.IO.File.AppendAllText(System.Environment.CurrentDirectory + "要发送的数据.txt", strV1.Trim().Replace("\0", "") + "\r\n", Encoding.UTF8); WriteLine(strV1); WriteLine(strV1.Length.ToString()); - //var dataV1 = Encoding.UTF8.GetBytes(strV1); - //var dataV1ForUdp = strV1.Last() == '|' ? Encoding.ASCII.GetBytes(strV1.Substring(0, strV1.Length - 1)) : dataV1; - //var dataCompressV1 = Encoding.UTF8.GetBytes($"*{ Convert.ToBase64String(CommonHelper.Compress(strV1)) }#"); - - - var data1 = new Data1(strV1); - var data1ForUdp = new Data1(strV1.Last() == '|' ? strV1.Substring(0, strV1.Length - 1) : strV1); - - //var watchList = string.Join('|', clients1.Where(c => c.IsWatch).Select(c => c.MemberId)); - //var strV2 = $"*l{{{ strV1 }}};w{{{ watchList }}}#"; - ////var dataCompressV2 = Encoding.UTF8.GetBytes($"{ Convert.ToBase64String(CommonHelper.Compress(strV2)) }"); - //var data2 = new Data1(strV2); + var data1 = new NetworkData(strV1); + var data1ForUdp = new NetworkData(strV1.Last() == '|' ? strV1.Substring(0, strV1.Length - 1) : strV1); SendDataSize = $"\t单客户端数据包V1:{ data1.GetBytes().Length / 1000D }KB,一共占用带宽:{ data1.GetBytes().Length / 1000D * clients1.Count }KB,压缩以后{ data1.GetBytes(true).Length / 1000D * clients1.Count }KB"; @@ -799,26 +786,22 @@ namespace OnlineUserPool.ViewModels { try { - if (item == null) - { - continue; - } - //if((item.Service is UdpService) ==false) - //{ - // continue; - //} + if (item == null) continue; + if (item.V != 1 && item.V != 2) { item.Service.Send(data, data.Length, item.IPEndPoint); continue; } + if (item.V == 1 && item.Service is UdpService) { item.Service.Send(data1ForUdp.GetBytes(), data1ForUdp.GetBytes().Length, item.IPEndPoint); } - else + + if(item.Service is TcpService) { - Data1 ddd = null;// = item.V == 1 ? ; + NetworkData ddd = null; if (item.V == 1) { ddd = data1; @@ -829,7 +812,7 @@ namespace OnlineUserPool.ViewModels var watchList1 = string.Join('|', clients1.Where(c => c.IsWatch && c.Competitionid == item.Competitionid).Select(c => c.MemberId)); var e = string.Join("|", list.Where(c => c.RoomId > 0 || c.FrameRate > 0).Select(c => $"{c.MemberId},{c.RoomId},{c.FrameRate},{c.TotalTicks}")); var strV21 = $"*l{{{ temp }}};w{{{ watchList1 }}};e{{{ e }}};#"; - ddd = new Data1(strV21); + ddd = new NetworkData(strV21); } else { @@ -951,10 +934,10 @@ namespace OnlineUserPool.ViewModels } } - public class Data1 + public class NetworkData { private string _txt = ""; - public Data1(string txt) + public NetworkData(string txt) { this._txt = txt; }