gpt4 book ai didi

c# - TcpListener 服务器循环空闲直到有挂起的连接

转载 作者:行者123 更新时间:2023-11-30 22:08:21 25 4
gpt4 key购买 nike

为了这个问题的目的,我做了一个 super 简化的例子:

using System;
using System.Net;
using System.Net.Sockets;

namespace Loop
{
class Program
{
public static void Main (string[] args)
{
TcpListener server = new TcpListener(IPAddress.Any, 1337);

server.Start();

Console.WriteLine("Starting listener on {0}:{1}", IPAddress.Any, 1337);

while (true)
{
if (server.Pending())
{
Console.WriteLine("Activity...");

Socket client = server.AcceptSocket();

IPEndPoint clientAddress = (IPEndPoint) client.RemoteEndPoint;

Console.WriteLine("Accepted client: {0}:{1}", clientAddress.Address, clientAddress.Port);

client.Close();

Console.WriteLine("Closed connection to: {0}:{1}", clientAddress.Address, clientAddress.Port);
}
else
{
// Currently takes 100% of my CPU (well, actually Core - 25%, but you get the idea).
// How do I idle (CPU @ 0%) the loop until pending connection?
}
}
}
}
}

评论中已经包含了这个问题,但是,是的,我如何让循环空闲直到有一个实际的挂起连接,这样我的 CPU 才不会被熔化?

当给定的套接字上有挂起的连接时,是否有一种方法可以仅在操作系统事件上监听和唤醒? (类似 libuv (node.js) 的东西,这就是我添加 的原因)

我的实际实现是针对一个相当基本的 Reactor 事件循环,但是,是的,我不知道如何使用 C# 监听操作系统事件(如果有的话)。

我知道 BeginAccept 和其他 Async 家族,但由于它们的多线程特性,这些人是 Not Acceptable 。

此外,我知道我可以在循环内简单地 Thread.Sleep,但我正在寻找基于事件的行为。

附言我正在使用 Mono,目标是 Linux 可执行文件。

最佳答案

我建议您只删除挂起连接的检查并让主线程阻塞(AcceptSocket 是一种阻塞方法)直到连接被接受:

while (true)
{
Console.WriteLine("Waiting for client to connect...");

Socket client = server.AcceptSocket(); // This is a blocking call...

Console.WriteLine("Client connected...");

IPEndPoint clientAddress = (IPEndPoint) client.RemoteEndPoint;

Console.WriteLine("Accepted client: {0}:{1}", clientAddress.Address, clientAddress.Port);

client.Close();

Console.WriteLine("Closed connection to: {0}:{1}", clientAddress.Address, clientAddress.Port);
}

关于c# - TcpListener 服务器循环空闲直到有挂起的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355655/

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