gpt4 book ai didi

c# - UDPClient 接收方法在服务中不起作用

转载 作者:行者123 更新时间:2023-11-30 19:50:27 25 4
gpt4 key购买 nike

我一直在试验 C# 中的 UDP 发送和接收,但遇到了一个奇怪的问题。该代码在控制台应用程序中运行良好,但当我尝试在服务中使用完全相同的代码时,client.Receive 方法被阻止。该服务正常运行并且不会中止,并且我已将日志记录写入文本文件,因此我知道它到达了接收。有人有主意吗?下面的代码...

public partial class Service1 : ServiceBase
{
private bool serviceStarted = false;
Thread listenerThread;

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
serviceStarted = false;
WriteLog("UDPListener Service Starting");

ThreadStart thread = new ThreadStart(StartListening);
listenerThread = new Thread(thread);

serviceStarted = true;
listenerThread.Start();
}

protected override void OnStop()
{
WriteLog("UDPListener Service Stopping");

serviceStarted = false;
listenerThread.Join(new TimeSpan(0, 0, 5));
}

private void StartListening()
{
WriteLog("Worker thread spawned.");

UdpClient client = new UdpClient(40000);

while (serviceStarted)
{
WriteLog("Service is started. Getting endpoint.");
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 40000);
WriteLog("Thread is listening...");

byte[] content = client.Receive(ref remoteIPEndPoint);
WriteLog("Receive unblocked.");

if (content.Length > 0)
{
string message = Encoding.ASCII.GetString(content);
WriteLog("UDPListener Message = " + message);
}
}
Thread.CurrentThread.Abort();
}

private void WriteLog(string strMessage)
{
FileStream filestream = new FileStream(@"c:\temp\UDPClientLog.txt",
FileMode.OpenOrCreate,
FileAccess.Write);
StreamWriter streamwriter = new StreamWriter(filestream);
streamwriter.BaseStream.Seek(0, SeekOrigin.End);

streamwriter.WriteLine(DateTime.Now.ToLongDateString() +
" at " +
DateTime.Now.ToLongTimeString() +
": " +
strMessage +
"\n");

streamwriter.Flush();
streamwriter.Close();
}
}

最佳答案

终于明白了。 Windows 防火墙阻止了传入连接,显然不允许该服务以交互方式请求取消阻止它的权限。

关于c# - UDPClient 接收方法在服务中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2298815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com