










using System; using System.Net; using System.Net.Sockets; using System.ServiceProcess; using System.Threading; using System.Threading.Tasks; namespace MyDelayService { public partial class DelayTaskService : ServiceBase { private Task _udpListenerTask; private CancellationTokenSource _cts; // UDP 监听端口(可自己改) private readonly int _udpPort = 8888; private UdpClient _udpServer; public DelayTaskService() { InitializeComponent(); ServiceName = "MyUdpEchoService"; } protected override void OnStart(string[] args) { WriteLog("===== UDP 回声服务已启动 ====="); _cts = new CancellationTokenSource(); _udpListenerTask = RunUdpEchoServerAsync(_cts.Token); } protected override void OnStop() { WriteLog("===== 服务正在停止 ====="); _cts?.Cancel(); _udpServer?.Close(); _udpListenerTask?.Wait(); WriteLog("===== 服务已停止 ====="); } /// <summary> /// UDP 回声服务端:收到什么就原样发回什么 /// </summary> private async Task RunUdpEchoServerAsync(CancellationToken token) { try { _udpServer = new UdpClient(_udpPort); WriteLog($"UDP 监听端口:{_udpPort}"); while (!token.IsCancellationRequested) { try { // 等待客户端消息 var result = await _udpServer.ReceiveAsync(); byte[] clientData = result.Buffer; IPEndPoint clientEp = result.RemoteEndPoint; string msg = System.Text.Encoding.UTF8.GetString(clientData); WriteLog($"【接收】{clientEp.Address}:{msg}"); // ====================== // 关键:原样返回给客户端 // ====================== await _udpServer.SendAsync(clientData, clientData.Length, clientEp); WriteLog($"【返回】{clientEp.Address}:{msg}"); } catch (Exception ex) { if (!token.IsCancellationRequested) WriteLog($"UDP 异常:{ex.Message}"); } } } catch (Exception ex) { WriteLog($"UDP 服务失败:{ex.Message}"); } } /// <summary> /// 写日志 /// </summary> public void WriteLog(string msg) { try { XLog.XTrace.WriteLine(msg); } catch { } } } }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。