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; public void RunServer(Action action) { //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) { var returnData = Encoding.UTF8.GetString(e.Data); Debug.WriteLine(returnData); 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); } public void Send(byte[] dgram, int bytes, IPEndPoint endPoint) { if(dgram == null || !dgram.Any()) { return; } foreach (var item in socket.GetClients()) { //try //{ if(socket.IsConnected(item) == false) { continue; } socket.Send(item, dgram); //} //catch(Exception e) //{ // Log.Error($"{ item.ToString() }:{ e.Message }\r\n{ e.StackTrace }"); //} } } public void Close() { _stop = true; socket.Dispose(); } } }