简体   繁体   English

python聊天客户端库

[英]python chat client lib

I'm trying to write a Python lib that will implement the client side of a certain chat protocol. 我正在尝试编写一个Python库,该库将实现某些聊天协议的客户端。

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). 我开始从服务器读取主循环并处理收到的命令,然后在这里我需要调用一个回调函数(例如on_messageon file_received等)。

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. 谢谢。

For a python app doing this, I wouldn't use threads. 对于执行此操作的python应用程序,我不会使用线程。 I would use a framework like Twisted . 我将使用Twisted之类的框架。

The docs have examples; 这些文档有示例; here's a chat example . 这是一个聊天示例

我会使用select模块,或者交替使用,但是select更具可移植性,在我看来,它更具Python风格。

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. 但是,asyncoreasynchat是达到相同目标的简单途径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM