|
| 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 | +} |
0 commit comments