Files
TouchSocket/examples/NamedPipe/NamedPipeServiceConsoleApp/Program.cs
2025-02-15 13:20:19 +08:00

99 lines
3.5 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.

//------------------------------------------------------------------------------
// 此代码版权除特别声明或在XREF结尾的命名空间的代码归作者本人若汝棋茗所有
// 源代码使用协议遵循本仓库的开源协议及附加协议若本仓库没有设置则按MIT开源协议授权
// CSDN博客https://blog.csdn.net/qq_40374647
// 哔哩哔哩视频https://space.bilibili.com/94253567
// Gitee源代码仓库https://gitee.com/RRQM_Home
// Github源代码仓库https://github.com/RRQM
// API首页https://touchsocket.net/
// 交流QQ群234762506
// 感谢您的下载和使用
//------------------------------------------------------------------------------
using TouchSocket.Core;
using TouchSocket.NamedPipe;
using TouchSocket.Sockets;
namespace NamedPipeServiceConsoleApp;
internal class Program
{
private static void Main(string[] args)
{
var service = CreateService();
Console.ReadKey();
}
private static NamedPipeService CreateService()
{
var service = new NamedPipeService();
service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接
service.Closed = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接
service.SetupAsync(new TouchSocketConfig()//载入配置
.SetPipeName("touchsocketpipe")//设置命名管道名称
.SetNamedPipeListenOptions(list =>
{
//如果想实现多个命名管道的监听即可这样设置一直Add即可。
list.Add(new NamedPipeListenOption()
{
Adapter = () => new NormalDataHandlingAdapter(),
Name = "TouchSocketPipe2"//管道名称
});
list.Add(new NamedPipeListenOption()
{
Adapter = () => new NormalDataHandlingAdapter(),
Name = "TouchSocketPipe3"//管道名称
});
})
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
a.AddConsoleLogger();//添加一个控制台日志注入注意在maui中控制台日志不可用
})
.ConfigurePlugins(a =>
{
a.Add<MyNamedPipePlugin>();
//a.Add();//此处可以添加插件
}));
service.StartAsync();//启动
service.Logger.Info("服务器已启动");
return service;
}
}
internal class MyNamedPipePlugin : PluginBase, INamedPipeConnectedPlugin, INamedPipeClosedPlugin, INamedPipeReceivedPlugin
{
private readonly ILog m_logger;
public MyNamedPipePlugin(ILog logger)
{
this.m_logger = logger;
}
public async Task OnNamedPipeClosed(INamedPipeSession client, ClosedEventArgs e)
{
this.m_logger.Info("Closed");
await e.InvokeNext();
}
public async Task OnNamedPipeConnected(INamedPipeSession client, ConnectedEventArgs e)
{
this.m_logger.Info("Connected");
await e.InvokeNext();
}
public async Task OnNamedPipeReceived(INamedPipeSession client, ReceivedDataEventArgs e)
{
this.m_logger.Info(e.ByteBlock.ToString());
if (client is INamedPipeSessionClient sessionClient)
{
await sessionClient.SendAsync(e.ByteBlock.Memory);
}
await e.InvokeNext();
}
}