Skip to content

Commit

Permalink
简化ApiServer,只需要一组网络服务器
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Apr 23, 2018
1 parent 2f3bb04 commit 36da7c9
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 112 deletions.
4 changes: 2 additions & 2 deletions NewLife.Core/Net/Handlers/StandardCodec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ public class StandardCodec : MessageCodec<IMessage>
public override Object Write(IHandlerContext context, Object message)
{
if (UserPacket && message is Packet pk)
{
message = new DefaultMessage { Payload = pk, Sequence = (Byte)Interlocked.Increment(ref _gid) };
}
else if (message is DefaultMessage msg && !msg.Reply && msg.Sequence == 0)
msg.Sequence = (Byte)Interlocked.Increment(ref _gid);

return base.Write(context, message);
}
Expand Down
1 change: 0 additions & 1 deletion NewLife.Core/NewLife.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@
<Compile Include="Remoting\ApiClient.cs" />
<Compile Include="Remoting\ApiException.cs" />
<Compile Include="Remoting\ApiHost.cs" />
<Compile Include="Remoting\ApiHttpServer.cs" />
<Compile Include="Remoting\ApiNetServer.cs" />
<Compile Include="Remoting\ApiServer.cs" />
<Compile Include="Remoting\ApiTest.cs" />
Expand Down
12 changes: 1 addition & 11 deletions NewLife.Core/Remoting/ApiNetServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NewLife.Collections;
using NewLife.Data;
using NewLife.Messaging;
using NewLife.Net;
Expand All @@ -29,7 +28,6 @@ public ApiNetServer()
{
Name = "Api";
UseSession = true;
//SessionTimeout = 10 * 60;
}

/// <summary>初始化</summary>
Expand Down Expand Up @@ -82,15 +80,7 @@ class ApiNetSession : NetSession<ApiNetServer>, IApiSession
public DateTime LastActive { get; set; }

/// <summary>所有服务器所有会话,包含自己</summary>
public virtual IApiSession[] AllSessions
{
get
{
// 需要收集所有服务器的所有会话
var svr = _Host as ApiServer;
return svr.Servers.SelectMany(e => e.AllSessions).ToArray();
}
}
public virtual IApiSession[] AllSessions => (_Host as ApiServer).Server.AllSessions;

/// <summary>开始会话处理</summary>
public override void Start()
Expand Down
77 changes: 17 additions & 60 deletions NewLife.Core/Remoting/ApiServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,12 @@ namespace NewLife.Remoting
/// <summary>应用接口服务器</summary>
public class ApiServer : ApiHost, IServer
{
#region 静态
/// <summary>协议到提供者类的映射</summary>
public static IDictionary<String, Type> Providers { get; } = new Dictionary<String, Type>(StringComparer.OrdinalIgnoreCase);

static ApiServer()
{
var ps = Providers;
ps.Add(NetType.Tcp + "", typeof(ApiNetServer));
ps.Add(NetType.Udp + "", typeof(ApiNetServer));
ps.Add(NetType.Unknown + "", typeof(ApiNetServer));
ps.Add(NetType.Http + "", typeof(ApiHttpServer));
ps.Add("ws", typeof(ApiHttpServer));
}
#endregion

#region 属性
/// <summary>是否正在工作</summary>
public Boolean Active { get; private set; }

/// <summary>服务器集合</summary>
public IList<IApiServer> Servers { get; } = new List<IApiServer>();
/// <summary>服务器</summary>
public IApiServer Server { get; set; }
#endregion

#region 构造
Expand All @@ -44,11 +29,11 @@ public ApiServer()

/// <summary>使用指定端口实例化网络服务应用接口提供者</summary>
/// <param name="port"></param>
public ApiServer(Int32 port) : this() => Add(port);
public ApiServer(Int32 port) : this() => Listen(port);

/// <summary>实例化</summary>
/// <param name="uri"></param>
public ApiServer(NetUri uri) : this() => Add(uri);
public ApiServer(NetUri uri) : this() => Listen(uri);

/// <summary>销毁时停止服务</summary>
/// <param name="disposing"></param>
Expand All @@ -63,15 +48,13 @@ protected override void OnDispose(Boolean disposing)
#region 启动停止
/// <summary>添加服务器</summary>
/// <param name="port"></param>
public IApiServer Add(Int32 port) => Add(new NetUri(NetType.Unknown, "", port));
public IApiServer Listen(Int32 port) => Listen(new NetUri(NetType.Unknown, "", port));

/// <summary>添加服务器</summary>
/// <param name="uri"></param>
public IApiServer Add(NetUri uri)
public IApiServer Listen(NetUri uri)
{
if (!Providers.TryGetValue(uri.Type + "", out var type)) return null;

var svr = type.CreateInstance() as IApiServer;
var svr = new ApiNetServer();
if (svr != null)
{
svr.Provider = this;
Expand All @@ -80,28 +63,7 @@ public IApiServer Add(NetUri uri)
if (!svr.Init(uri.ToString())) return null;
}

Servers.Add(svr);

return svr;
}

/// <summary>添加服务器</summary>
/// <param name="config"></param>
public IApiServer Add(String config)
{
var protocol = config.Substring(null, "://");
if (!Providers.TryGetValue(protocol, out var type)) return null;

var svr = type.CreateInstance() as IApiServer;
if (svr != null)
{
svr.Provider = this;
svr.Log = Log;

if (!svr.Init(config)) return null;
}

Servers.Add(svr);
Server = svr;

return svr;
}
Expand All @@ -116,18 +78,16 @@ public virtual void Start()

Encoder.Log = EncoderLog;

Log.Info("启动{0},共有服务器{1}", GetType().Name, Servers.Count);
Log.Info("启动{0},服务器 {1}", GetType().Name, Server);
Log.Info("编码:{0}", Encoder);
//Log.Info("处理:{0}", Handler);

foreach (var item in Servers)
{
if (item.Handler == null) item.Handler = Handler;
if (item.Encoder == null) item.Encoder = Encoder;
item.Provider = this;
item.Log = Log;
item.Start();
}
var svr = Server;
if (svr.Handler == null) svr.Handler = Handler;
if (svr.Encoder == null) svr.Encoder = Encoder;
svr.Provider = this;
svr.Log = Log;
svr.Start();

ShowService();

Expand All @@ -141,10 +101,7 @@ public virtual void Stop(String reason)
if (!Active) return;

Log.Info("停止{0} {1}", GetType().Name, reason);
foreach (var item in Servers)
{
item.Stop(reason ?? (GetType().Name + "Stop"));
}
Server.Stop(reason ?? (GetType().Name + "Stop"));

Active = false;
}
Expand All @@ -159,7 +116,7 @@ public override Object GetService(Type serviceType)
// 服务类是否当前类的基类
if (GetType().As(serviceType)) return this;

if (serviceType == typeof(IServer)) return this;
//if (serviceType == typeof(IServer)) return this;

return base.GetService(serviceType);
}
Expand Down
51 changes: 30 additions & 21 deletions NewLife.Core/Remoting/ApiTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ public static void Main()

private static void TestServer()
{
var svr = new ApiServer(3344);
svr.Add("http://*:888/");
svr.Log = XTrace.Log;
svr.EncoderLog = XTrace.Log;
//svr.Encoder = new JsonEncoder();
var svr = new ApiServer(3344)
{
Log = XTrace.Log,
EncoderLog = XTrace.Log
};
svr.Register<HelloController>();

var ns = svr.Servers[0] as NetServer;
ns.LogSend = true;
ns.LogReceive = true;
//var ns = svr.Server as NetServer;
//ns.LogSend = true;
//ns.LogReceive = true;

svr.Start();

Expand All @@ -41,34 +41,43 @@ private static void TestServer()

private static async void TestClient()
{
var client = new ApiClient("tcp://127.0.0.1:3344");
//var client = new ApiClient("udp://127.0.0.1:3344");
//var client = new ApiClient("http://127.0.0.1:888");
//var client = new ApiClient("ws://127.0.0.1:888");
client.Log = XTrace.Log;
client.EncoderLog = XTrace.Log;
//client.Encoder = new JsonEncoder();

var sc = client.Client;
sc.LogSend = true;
sc.LogReceive = true;
var client = new ApiClient("tcp://127.0.0.1:3344")
{
Log = XTrace.Log,
EncoderLog = XTrace.Log
};

//var sc = client.Client;
//sc.LogSend = true;
//sc.LogReceive = true;

client.Open();

var msg = "NewLifeX";
var rs = await client.InvokeAsync<String>("Hello/Say", new { msg });
Console.WriteLine();
var rs = await client.InvokeAsync<String>("Say", new { msg });
XTrace.WriteLine(rs);

Console.WriteLine();
rs = await client.InvokeAsync<String>("Hello/Eat", new { msg });
XTrace.WriteLine(rs);

Console.WriteLine();
rs = await client.InvokeAsync<String>("Sleep", new { msg });
XTrace.WriteLine(rs);

Console.WriteLine();
try
{
msg = "报错";
rs = await client.InvokeAsync<String>("Hello/Say", new { msg });
rs = await client.InvokeAsync<String>("Say", new { msg });
}
catch (ApiException ex)
{
XTrace.WriteLine("服务端发生 {0} 错误:{1}", ex.Code, ex.Message);
}

Console.WriteLine();
var apis = await client.InvokeAsync<String[]>("Api/All");
Console.WriteLine(apis.Join(Environment.NewLine));

Expand Down
22 changes: 6 additions & 16 deletions NewLife.Core/Remoting/IApiHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,7 @@ public Object Execute(IApiSession session, String action, IDictionary<String, Ob
var controller = session.CreateController(api);
if (controller == null) throw new ApiException(403, "无法创建名为[{0}]的服务!".F(api.Name));

if (controller is IApi) (controller as IApi).Session = session;

//// 服务端需要检查登录授权
//if (Host is ApiServer svrHost && !svrHost.Anonymous)
//{
// if (controller.GetType().GetCustomAttribute<AllowAnonymousAttribute>() == null &&
// api.Method.GetCustomAttribute<AllowAnonymousAttribute>() == null)
// {
// if (session.UserSession == null || !session.UserSession.Logined) throw new ApiException(401, "未登录!");
// }
//}
if (controller is IApi capi) capi.Session = session;

// 服务设置优先于全局主机
var svr = session.GetService<IApiServer>();
Expand Down Expand Up @@ -82,7 +72,6 @@ public Object Execute(IApiSession session, String action, IDictionary<String, Ob
ControllerContext.Current = actx;

// 执行动作前的过滤器
//OnExecuting(actx, fs);
if (controller is IActionFilter filter)
{
filter.OnActionExecuting(actx);
Expand All @@ -103,20 +92,21 @@ public Object Execute(IApiSession session, String action, IDictionary<String, Ob
{
etx = new ExceptionContext(ctx) { Exception = ex, Result = rs };
filter.OnException(etx);
rs = etx.Result;
rs = etx.Result ?? etx.Exception ?? ex;
}
else
rs = ex;

Host.WriteLog("执行{0}出错!{1}", action, ex.Message);

// 如果异常没有被拦截,继续向外抛出
if (!etx.ExceptionHandled) throw;
if (etx != null && !etx.ExceptionHandled) throw;

return rs = etx.Result;
return rs;
}
finally
{
// 执行动作后的过滤器
//rs = OnExecuted(ctx, etx, fs, rs);
if (controller is IActionFilter filter)
{
var atx = new ActionExecutedContext(etx ?? ctx) { Result = rs };
Expand Down
2 changes: 1 addition & 1 deletion XCoder/XApi/FrmMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ void ShowStat(Object state)
if (_Client != null)
msg = _Client.Client?.GetStat();
else if (_Server != null)
msg = (_Server.Servers[0] as NetServer)?.GetStat();
msg = (_Server.Server as NetServer)?.GetStat();

if (!msg.IsNullOrEmpty() && msg != _lastStat)
{
Expand Down

0 comments on commit 36da7c9

Please sign in to comment.