python 聊天客户端库

发布于 2024-08-09 09:10:18 字数 308 浏览 1 评论 0原文

我正在尝试编写一个Python 库来实现某个聊天协议的客户端。

连接到服务器后,
我启动主循环,从服务器读取数据并处理接收到的命令,在这里我需要调用回调函数(例如 on_messageon file_received 等)。

我应该如何实施这个?
是否应该为每个回调函数启动一个新线程?因为也许某些回调需要一些时间才能返回,并且我会超时。
另外,
如果我从服务器读取的主循环位于一个线程中,我可以从另一个线程写入套接字(向服务器发送消息)吗?
或者有更好的方法吗? 谢谢。

I'm trying to write a Python lib that will implement the client side of a certain chat protocol.

After I connect to the server,
I start the main loop where I read from the server and handle received commands and here I need to call a callback function (like on_message or on file_received, etc).

How should I go about implementing this?
Should a start a new thread for each callback function? As maybe some callbacks will take some time to return and I will timeout.
Also,
If the main loop where I read from the server is in a thread can I write to the socket from another thread(send messages to the server)?
Or is there a better approach?
Thanks.

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

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

发布评论

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

评论(3

稚气少女 2024-08-16 09:10:18

对于执行此操作的 python 应用程序,我不会使用线程。我会使用像 Twisted 这样的框架。

该文档有示例; 这是一个聊天示例

For a python app doing this, I wouldn't use threads. I would use a framework like Twisted.

The docs have examples; here's a chat example.

我们的影子 2024-08-16 09:10:18

我会使用 select 模块,或者交替使用,但是 select 更便携,而且在我看来更Pythonic。

I would use the select module, or alternately twisted, however select is a bit more portable, and to my mind somewhat more pythonic.

天暗了我发光 2024-08-16 09:10:18

线程在这里只是一个不必要的复杂化,如果您不熟悉如何正确使用它们,将会导致隐蔽的错误。 asyncoreasynchat 是实现同一目标的简单途径。

Threads are just an unnecessary complication here and will lead to obscure bugs if you're not familiar with how to use them correctly. asyncore or asynchat are simple routes to the same goal, however.

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