powerfun-new-net/Services/TcpService1.cs
andy 0e931a3ac9 一些功能调整
增加tcp协议支持;
增加模拟多用户的功能;
2021-01-18 20:24:19 +08:00

119 lines
3.8 KiB
C#

using NetCoreServer;
using OnlineUserPool.Model;
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<IPEndPoint, MsgModel, IService> action)
{
//throw new NotImplementedException();
//_action = action;
_server = new PfTcpServer(IPAddress.Any, 11001, (ip, model)=> {
action(ip, model, this);
});
//_server.OptionNoDelay = true;
_server.Start();
}
public void Send(byte[] dgram, int bytes, IPEndPoint endPoint)
{
if (dgram == null || !dgram.Any())
{
return;
}
_server.Multicast(dgram);
}
class PfTcpServer : TcpServer
{
Action<IPEndPoint, MsgModel> _action;
public PfTcpServer(IPAddress address, int port, Action<IPEndPoint, MsgModel> action) :base(address, port)
{
_action = action;
}
protected override TcpSession CreateSession()
{
//return base.CreateSession()
return new PfTcpSession(this, _action);
}
protected override void OnError(SocketError error)
{
//base.OnError(error);
Debug.WriteLine(error);
}
}
class PfTcpSession : TcpSession
{
Action<IPEndPoint, MsgModel> _action;
public PfTcpSession(TcpServer server, Action<IPEndPoint, MsgModel> action) : base(server) {
_action = action;
}
protected override void OnConnected()
{
//base.OnConnected();
Debug.WriteLine("有新的Tcp连接");
}
protected override void OnDisconnected()
{
//base.OnDisconnected();
Debug.WriteLine("Tcp断开连接");
}
protected override void OnReceived(byte[] buffer, long offset, long size)
{
//base.OnReceived(buffer, offset, size);
var returnData = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
//Debug.WriteLine(returnData);
//Log.Information(returnData + "\r\n");
try
{
//var msg = Newtonsoft.Json.JsonConvert.DeserializeObject<MsgModel>(returnData);
//var ipEndPoint = IPEndPoint.Parse(this.Socket.RemoteEndPoint.ToString());
//_action(ipEndPoint, msg);
foreach (var item in returnData.Split(new string[] { "}" }, StringSplitOptions.RemoveEmptyEntries))
{
//if (string.IsNullOrWhiteSpace(item)) continue;
var msg = Newtonsoft.Json.JsonConvert.DeserializeObject<MsgModel>(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);
}
}
}
}