|
| 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 | +class MockSendReceiveSocketServerService(ILogger<MockReceiveSocketServerService> 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, 8810); |
| 24 | + server.Start(); |
| 25 | + while (stoppingToken is { IsCancellationRequested: false }) |
| 26 | + { |
| 27 | + try |
| 28 | + { |
| 29 | + var client = await server.AcceptTcpClientAsync(stoppingToken); |
| 30 | + _ = Task.Run(() => MockSendAsync(client, stoppingToken), stoppingToken); |
| 31 | + } |
| 32 | + catch { } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + private async Task MockSendAsync(TcpClient client, CancellationToken stoppingToken) |
| 37 | + { |
| 38 | + // 方法目的: |
| 39 | + // 接收到数据后会送当前时间戳数据包到客户端 |
| 40 | + await using var stream = client.GetStream(); |
| 41 | + while (stoppingToken is { IsCancellationRequested: false }) |
| 42 | + { |
| 43 | + try |
| 44 | + { |
| 45 | + // 接收数据 |
| 46 | + var len = await stream.ReadAsync(new byte[1024], stoppingToken); |
| 47 | + if (len == 0) |
| 48 | + { |
| 49 | + // 断开连接 |
| 50 | + break; |
| 51 | + } |
| 52 | + // 模拟服务,对接收到的消息未做处理 |
| 53 | + // 模拟一发一收的通讯方法 |
| 54 | + var data = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); |
| 55 | + await stream.WriteAsync(data, stoppingToken); |
| 56 | + } |
| 57 | + catch (OperationCanceledException) { break; } |
| 58 | + catch (IOException) { break; } |
| 59 | + catch (SocketException) { break; } |
| 60 | + catch (Exception ex) |
| 61 | + { |
| 62 | + logger.LogError(ex, "MockSendReceiveSocketServerService encountered an error while sending data."); |
| 63 | + break; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments