Files
FunGameServer-Test/plugins/FunGame.Server.Plugins.Example/ExamplePlugin.cs
T
2026-08-28 19:44:46 +08:00

82 lines
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using FunGame.Server.Contracts.Gaming;
using FunGame.Server.Contracts.Networking;
using FunGame.Server.Contracts.Payloads;
using FunGame.Server.Contracts.Plugins;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FunGame.Server.Plugins.Example;
/// <summary>
/// 示例服务器插件(合并 v2 的 WebAPIPlugin 与 GameModuleServer)<para/>
/// - HTTP 端点:GET /plugin/example/hello<para/>
/// - WS 消息处理器:example.echo<para/>
/// - 对局模式:HandleGamingMessage(example.cheer)
/// </summary>
public class ExamplePlugin : IServerPlugin
{
private ILogger? _logger;
public string Name => "example";
public string Version => "1.2.0";
public string Author => "FunGame.Server";
public string Description => "示例服务器插件:演示 HTTP 端点、WS 消息处理器、对局模式与热重载";
public void OnLoad(IServiceProvider services)
{
_logger = services.GetService<ILoggerFactory>()?.CreateLogger("Plugin.example");
_logger?.LogInformation("ExamplePlugin v{Version} 已加载", Version);
}
public void OnUnload()
{
_logger?.LogInformation("ExamplePlugin 即将卸载(端点与消息处理器随后注销)");
}
public void ConfigureEndpoints(IPluginHttpHandlerRegistry http, IMessageHandlerRegistry messages)
{
// GET /plugin/example/hello
http.Register("GET", "hello", this, async context =>
{
await context.Response.WriteAsJsonAsync(ApiResponse.Success(new
{
message = "来自示例插件的问候(热重载后 v1.2.0)",
plugin = Name,
version = Version,
time = DateTime.Now
}));
});
// GET /plugin/example/info
http.Register("GET", "info", this, async context =>
{
await context.Response.WriteAsJsonAsync(ApiResponse.Success(new
{
name = Name,
version = Version,
author = Author,
description = Description
}));
});
// WS:example.echo —— 原样回显负载
messages.Register("example.echo", this, async (client, message) =>
{
return MessageEnvelope.Reply(message, message.Data);
});
}
public Task<Dictionary<string, object>?> HandleGamingMessage(IGameSession session, string type, Dictionary<string, object> data)
{
if (type == "example.cheer")
{
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
{
["message"] = $"插件 {Name} 收到对局消息(对局 {session.Id},回合 {session.Queue.TotalRound})"
});
}
return Task.FromResult<Dictionary<string, object>?>(null);
}
}