c 语言中发送和监听的 tcp 客户端:概念

发布于 2025-01-07 00:04:07 字数 312 浏览 0 评论 0原文

我正在考虑用 C 语言制作一个 tcp 客户端。 但在开始之前我想听听你的一些建议。

客户端用于控制灯光和其他设备。

使用此客户端,我需要发送命令,但我也可以在有人关灯时接收事件。

只需使用套接字发送命令是没有问题的。 但同时我必须阅读传入的包裹。

如何最好地解决这个问题? 我需要使用线程还是可以用 libevent 之类的东西来解决这个问题?

大多数人如何实现这样的事情?

这个库应该尽可能地可移植。 (linux,unix,windows,...)

(我不是在寻找代码,只是寻找最好的方法)

I'm looking into making a tcp client in C.
But before I start I would like some advise from you.

The client is for controlling lights and other devices.

With this client I will need to send commands, but I can also receive events when a light is turned off by someone.

Just sending commands with sockets is no problem.
But at the same time I have to read for incoming packages.

How is this best solved?
Do I need to use threads or can I solve this with something like libevent?

How do most people implement something like this?

This library should be as portable as possible. (linux, unix, windows, ...)

(I'm not looking for code, but just a best approach)

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

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

发布评论

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

评论(2

画尸师 2025-01-14 00:04:07

检查套接字是否有传入数据

恕我直言,使用 libevent 超出了您的目的。这很好,但要认识到它的威力还有很长的路要走。实际上,libevent 是 select(2) 或其改进后继者 epoll(2) 等的包装器。

BSD sockets are bidirectional, and you can check if your socket has an incoming data or not by select(2)

IMHO using libevent is too much for your purpose. It's nice but you have long way to go to realize its power. Actually libevent is a wrapper for select(2) or its improved successor epoll(2) etc.

嘿嘿嘿 2025-01-14 00:04:07

我认为你必须有两个连接,一个用于发送命令,一个用于在有人关灯时从服务器获取响应,大多数时候两个连接都处于睡眠状态。如果只创建一个连接,则必须每隔xx毫秒查询一次灯状态,大多数时候会浪费带宽。如果您的应用程序不严重,服务器可以在有人关灯时使用 UDP 通知客户端,该解决方案只需要一个实时 TCP 连接。

I think you have to have two connections, one for sending command, one for getting respond from server when someone turns off light, most of time two conns are sleep. if you only create one connection, you have to query light status every xx ms, most of time it wastes bandwidth. if your app is not serious, server can use UDP to notify client when the light is turned off by someone, which solution only needs one live TCP connection.

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