C 中动态帐户连接的最佳解决方案?
我不太熟悉 C 设计模式并正在寻找以下问题的最佳解决方案。我想写一个基于 libpurple 的小聊天客户端。
在运行该程序时,我希望能够连接和断开多个即时消息帐户。连接和断开连接调用应该通过命令行传递,但等待使用 gets() 输入;这不是解决方案,因为程序应该一直运行,从已连接的即时消息帐户获取新消息。
I'm not very familiar with C design patterns and searching for the best solution for the following problem. I want to write a little chat client based on libpurple.
While running the program I want to be able to connect and disconnect several instant message accounts. The connect and disconnect calls should be passed over command line, but waiting for input with gets(); is no solution, because the program should run all the time getting new messages from the already connected instant message accounts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想使用
poll
(或select
)来处理事件。因此,建立连接后,您将拥有文件描述符,此外您还有标准输入,其中还有来自操作系统的文件描述符(即 0),并且您可以将所有这些文件描述符传递给 poll code>,当任何文件描述符上有传入数据时,它会通知您。示例代码:您没有提到操作系统。这适用于 POSIX(OS X、Linux、带有 mingw 的 Windows)。如果您需要使用Win32 API,它看起来会有点不同,但原理是相同的。
You probably want to use
poll
(orselect
) for handling the events. So after establishing the connections, you have the file descriptors, and in addition you have the standard input, which also has a file descriptor from the OS (namely 0), and you can pass all those file descriptors topoll
, which notifies you when there is incoming data on any of the file descriptors. Example code:You didn't mention the OS. This works for POSIX (OS X, Linux, Windows with mingw). If you need to use the Win32 API, it'll look a bit different but the principle is the same.
查看选择(2)。我不太确定 libpurple 是如何工作的,但如果它允许通过文件描述符(如文件或套接字)进行通知,那么 select 就是您的解决方案。
您还可以尝试使用 pthread_create(3) 创建单独的线程。这样它就可以阻止获取(或其他),而程序的其余部分则执行它的操作。
Check out select(2). I'm not really sure how libpurple works, but if it allows notification via file-descriptor (like a file or socket), then select is your solution.
You could also try creating a seperate thread with pthread_create(3). That way it can block on gets (or whatever) while the rest of your program does it's thing.