Skip to content

Commit f9c42cf

Browse files
committed
doc: 增加后台服务
1 parent 3c17b32 commit f9c42cf

File tree

3 files changed

+78
-3
lines changed

3 files changed

+78
-3
lines changed

src/BootstrapBlazor.Server/Extensions/ServiceCollectionExtensions.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ void Invoke(BootstrapBlazorOptions option)
4545
services.AddTaskServices();
4646
services.AddHostedService<ClearTempFilesService>();
4747
services.AddHostedService<MockOnlineContributor>();
48-
services.AddHostedService<MockSocketServerService>();
48+
services.AddHostedService<MockReceiveSocketServerService>();
49+
services.AddHostedService<MockCustomProtocolSocketServerService>();
4950

5051
// 增加通用服务
5152
services.AddBootstrapBlazorServices();
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the Apache 2.0 License
3+
// See the LICENSE file in the project root for more information.
4+
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone
5+
6+
using System.Net;
7+
using System.Net.Sockets;
8+
9+
namespace Longbow.Tasks.Services;
10+
11+
/// <summary>
12+
/// 模拟 Socket 服务端服务类
13+
/// </summary>
14+
internal class MockCustomProtocolSocketServerService(ILogger<MockCustomProtocolSocketServerService> logger) : BackgroundService
15+
{
16+
/// <summary>
17+
/// 运行任务
18+
/// </summary>
19+
/// <param name="stoppingToken"></param>
20+
/// <returns></returns>
21+
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
22+
{
23+
var server = new TcpListener(IPAddress.Loopback, 8900);
24+
server.Start();
25+
while (stoppingToken is { IsCancellationRequested: false })
26+
{
27+
try
28+
{
29+
var client = await server.AcceptTcpClientAsync(stoppingToken);
30+
_ = Task.Run(() => OnDataHandlerAsync(client, stoppingToken), stoppingToken);
31+
}
32+
catch { }
33+
}
34+
}
35+
36+
private async Task OnDataHandlerAsync(TcpClient client, CancellationToken stoppingToken)
37+
{
38+
// 方法目的:
39+
// 收到消息后发送自定义通讯协议的响应数据
40+
// 响应头 + 响应体
41+
await using var stream = client.GetStream();
42+
while (stoppingToken is { IsCancellationRequested: false })
43+
{
44+
try
45+
{
46+
// 接收数据
47+
var len = await stream.ReadAsync(new byte[1024], stoppingToken);
48+
if (len == 0)
49+
{
50+
// 断开连接
51+
break;
52+
}
53+
54+
// 实际应用中需要解析接收到的数据进行处理,本示例中仅模拟接收数据后发送响应数据
55+
56+
// 发送响应数据
57+
// 响应头: 4 字节表示响应体长度 [0x32, 0x30, 0x32, 0x35]
58+
// 响应体: 8 字节当前时间戳字符串
59+
var data = new byte[12];
60+
"2025"u8.ToArray().CopyTo(data, 0);
61+
System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("ddHHmmss")).CopyTo(data, 4);
62+
await stream.WriteAsync(data, stoppingToken);
63+
}
64+
catch (OperationCanceledException) { break; }
65+
catch (IOException) { break; }
66+
catch (SocketException) { break; }
67+
catch (Exception ex)
68+
{
69+
logger.LogError(ex, "MockCustomProtocolSocketServerService encountered an error while sending data.");
70+
break;
71+
}
72+
}
73+
}
74+
}

src/BootstrapBlazor.Server/Services/MockSocketServerService.cs renamed to src/BootstrapBlazor.Server/Services/MockReceiveSocketServerService.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ namespace Longbow.Tasks.Services;
1111
/// <summary>
1212
/// 模拟 Socket 服务端服务类
1313
/// </summary>
14-
internal class MockSocketServerService(ILogger<MockSocketServerService> logger) : BackgroundService
14+
class MockReceiveSocketServerService(ILogger<MockReceiveSocketServerService> logger) : BackgroundService
1515
{
1616
/// <summary>
1717
/// 运行任务
@@ -52,7 +52,7 @@ private async Task MockSendAsync(TcpClient client, CancellationToken stoppingTok
5252
catch (SocketException) { break; }
5353
catch (Exception ex)
5454
{
55-
logger.LogError(ex, "MockSocketServerService encountered an error while sending data.");
55+
logger.LogError(ex, "MockReceiveSocketServerService encountered an error while sending data.");
5656
break;
5757
}
5858
}

0 commit comments

Comments
 (0)