服务不是单独的,总要和其他系统进行信息交互,记录一个解决方案(方便,好用)
新建控制台,然后安装Topshelf和TouchSocket,作为服务
示例代码:
namespace TestServer
{
class Program
{
static void Main(string[] args)
{
// 配置和运行宿主服务
HostFactory.Run(x =>
{
// 指定服务类型。这里设置为 CacheService
x.Service<CacheService>(s =>
{
// 通过 new CacheService() 构建一个服务实例
s.ConstructUsing(name => new CacheService());
// 当服务启动后执行什么
s.WhenStarted(tc => tc.Start());
// 当服务停止后执行什么
s.WhenStopped(tc => tc.Stop());
});
// 服务用本地系统账号来运行
x.RunAsLocalSystem();
// 服务描述信息
x.SetDescription("缓存服务");
// 服务显示名称
x.SetDisplayName("CacheService");
// 服务名称
x.SetServiceName("CacheService");
});
}
}
public class CacheService
{
TcpService service = new TcpService();
public CacheService()
{
service.Connecting = (client, e) => { };//有客户端正在连接
service.Connected = (client, e) => { };//有客户端连接
service.Disconnected = (client, e) => { };//有客户端断开连接
service.Received = (client, byteBlock, requestInfo) =>
{
//从客户端收到信息
string mes = byteBlock.ToString();
Console.WriteLine($"已从{client.ID}接收到信息:{mes}");
client.Send(mes);//将收到的信息直接返回给发送方
//client.Send("id",mes);//将收到的信息返回给特定ID的客户端
var clients = service.GetClients();
foreach (var targetClient in clients)//将收到的信息返回给在线的所有客户端。
{
if (targetClient.ID != client.ID)
{
targetClient.Send(mes);
}
}
};
}
public void Start()
{
service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts(new IPHost[] { new IPHost("127.0.0.1:7789"), new IPHost(7790) }))//同时监听两个地址
.Start();//启
}
public void Stop()
{
service.Stop();
}
}
}
新建MVC系统,安装TouchSocket,通讯一下
TcpClient tcpClient = new TcpClient();
tcpClient.Connected = (client, e) => { };//成功连接到服务器
tcpClient.Disconnected = (client, e) => { };//从服务器断开连接,当连接不成功时不会触发。
tcpClient.Received = (client, byteBlock, requestInfo) =>
{
//从服务器收到信息
string mes = Encoding.UTF8.GetString(byteBlock.Buffer, 0, byteBlock.Len);
Console.WriteLine($"接收到信息:{mes}");
};
//声明配置
TouchSocketConfig config = new TouchSocketConfig();
config.SetRemoteIPHost(new IPHost("127.0.0.1:7789"))
.UsePlugin()
.SetBufferLength(1024 * 10);
//载入配置
tcpClient.Setup(config);
tcpClient.Connect();
tcpClient.Send("RRQM");
根据需要修改即可使用了
标签:tcpClient,通讯,service,CacheService,TouchSocket,client,mes,Topshelf,new From: https://www.cnblogs.com/itljf/p/17626945.html