适合中等简单 TCP 服务器的良好架构

发布于 2024-12-29 03:41:19 字数 510 浏览 1 评论 0原文

我计划在 Linux 上用 C 语言实现一个特殊用途的 TCP 服务器。经过一番研究后,看起来有几种方法可以做到这一点,包括单线程、每个连接一个线程等等。对于套接字,有数据报与流、阻塞与非阻塞等选项。

大多数通信将如下所示:

Client: request id [request info]
Server: status id [response info]

Client: request id [request info]
Server: status id [response info]
Client: additional request id [request info]
Server: status id [response info]

其中所有内容都 <1kB,并且大多数内容都 <512B。然而,短时间内可能会有许多个人请求。

那么,如何设置服务器才能最有效地工作(即不占用资源,不拒绝客户端请求)?

I am planning on implementing a special purpose TCP server in C on Linux. After doing a little research, it looks like there are a few ways to do this, including single threaded, one thread per connection, and others. For the sockets, there are options like datagram vs stream, and blocking vs non-blocking.

Most of the communication is going to look like:

Client: request id [request info]
Server: status id [response info]

or

Client: request id [request info]
Server: status id [response info]
Client: additional request id [request info]
Server: status id [response info]

Where everything is <1kB and most things are <512B. There may be many individual requests in a short time, however.

So, how do I set up the server so it works most effectively (ie, doesn't hog resources, doesn't deny client requests)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄与心 2025-01-05 03:41:19

我认为你的问题归结为性能。是吗?

如果是这样,那么三个问题:

  • 您的服务器将处理的平均/最大客户端数量是多少?
  • 连接是持久的,还是客户端针对每个 X 请求进行连接?
  • 当客户端发送新请求时涉及多少处理?

无论如何,我会从简单开始。使其成为非阻塞且单线程的。对它进行分析和压力测试。然后,如果您对所呈现的性能不满意,请找出根本原因并尝试修复它。作为最终选择,将其扩展到每个处理器核心一个工作线程。

如果您不关心可靠性和交付顺序,您可能需要使用 UDP。

I think your question boils down to performance. Does it?

If so, three questions:

  • What's the average/maximum number of clients your server will be handling?
  • Is the connection persistent, or clients connect for every X requests?
  • How much processing is involved when a client sends a new request?

Anyway, I'd start simple. Make it non-blocking, and single threaded. Profile and stress-test it. Then, if you're not happy with the presented performance, identify the root cause and try to fix it. As ultimate option, scale it to one worker thread per processor core.

If you don't care about reliability and order of delivery, you might want to use UDP.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文