尝试修复在for循环满足之前循环不会继续的friends代码。我觉得readbuffer有点问题。基本上,我们希望while循环能够连续循环,但是如果for循环满意,就运行它。如果有人能帮助我了解readbuffer和temp中发生了什么,我将非常感谢
以下是片段:
s = openSocket()
joinRoom(s)
readbuffer = ""
while True:
readbuffer = readbuffer + s.recv(1024)
temp = string.split(readbuffer, "\n")
readbuffer = temp.pop()
for line in temp:
user = getUser(line)
message = getMessage(line)
根据我对您问题的理解,您希望在继续接收数据包的同时执行for循环
我不确定您在
getUser
和getMessage
中做了什么,如果其中有I/O操作(读/写文件、DB I/O、发送/接收…),您可以使用python中的async
特性来编写异步程序(参见:https://docs.python.org/3/library/asyncio-task.html)但是,我假设您只是从
line
中提取一个元素,它不涉及I/O操作。在这种情况下,async
就没用了。如果getUser
和getMessage
确实占用了太多CPU时间,那么可以将for循环放入一个新线程,使字符串操作成为非阻塞的(参见:https://docs.python.org/3/library/threading.html)更新
当然,这不是解决这个问题的典型方法,对于初学者和简单的作业来说,这更容易理解
一个更好的方法是使用类似于Future的东西,使send/recv异步,并将回调传递给它,这样它就可以将接收到的数据传递给回调。如果您想将繁重的CPU工作负载转移到另一个线程创建一个无休止的循环(例程),只需在回调或其他地方创建一个
Thread
,具体取决于您的体系结构设计我为我的网络编程课程实现了一个轻量级的distributed computing framework。如果有人感兴趣的话,我为这个项目写了我自己的future class
相关问题 更多 >
编程相关推荐