Python套接字助手

2024-09-25 08:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试修复在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)

Tags: 代码intrueforstringlinepoptemp
1条回答
网友
1楼 · 发布于 2024-09-25 08:25:46

根据我对您问题的理解,您希望在继续接收数据包的同时执行for循环

我不确定您在getUsergetMessage中做了什么,如果其中有I/O操作(读/写文件、DB I/O、发送/接收…),您可以使用python中的async特性来编写异步程序(参见:https://docs.python.org/3/library/asyncio-task.html

但是,我假设您只是从line中提取一个元素,它不涉及I/O操作。在这种情况下,async就没用了。如果getUsergetMessage确实占用了太多CPU时间,那么可以将for循环放入一个新线程,使字符串操作成为非阻塞的(参见:https://docs.python.org/3/library/threading.html

from threading import Thread

def getUserProfile(lines, profiles, i):
    for line in lines:
        user = getUser(line)
        message = getMessage(line)
        profiles.append((user, message))


profiles = []
threads = []
s = openSocket()
joinRoom(s)

while True:
    readbuffer = s.recv(1024)
    lines = readbuffer.decode('utf-8').split('\n')
    t = Thread(target=getUserProfile, args=(lines, profiles, count))
    t.run()
    threads.append(t)



# If somehow the loop may be interrupted, 
# These two lines should be added to wait for all threads to finish
for th in threads:
  th.join() # will block main thread until all threads are terminated

更新

当然,这不是解决这个问题的典型方法,对于初学者和简单的作业来说,这更容易理解

一个更好的方法是使用类似于Future的东西,使send/recv异步,并将回调传递给它,这样它就可以将接收到的数据传递给回调。如果您想将繁重的CPU工作负载转移到另一个线程创建一个无休止的循环(例程),只需在回调或其他地方创建一个Thread,具体取决于您的体系结构设计

我为我的网络编程课程实现了一个轻量级的distributed computing framework。如果有人感兴趣的话,我为这个项目写了我自己的future class

相关问题 更多 >