基于Python UDPBase的套接字在一个线程中只能发送接收一次

2024-09-27 07:34:03 发布

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

python:udp套接字在一个线程中只发送接收一次

但是我可以使用udp套接字在一个循环中发送多个请求,而不需要线程

class mydo(threading.Thread):
    def __init__(self,count):
        super(mydo, self).__init__()
        self.count = count
    def run(self):
        while self.count > 0:
            self.count -= 1
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            request = json.dumps({"Request": ["setMessage", "Hello !!"]})
            if 0 == self.count:
                request = json.dumps({"Request": ["setMessage", "Hello @@@"]})
            sock.sendto(request, ('127.0.0.1', 8080))
            tmp = sock.recvfrom(1024)
            sock.close()
numOfThreads = 1
threads = []
count = 50
for i in range(numOfThreads):
    t = mydo(count)
    threads.append(t)
for t in threads:
    t.start()

在线程中,套接字只发送最后一个请求(预期50个),服务器只接收最后一个请求


Tags: selfjsoninitrequestdefcountsocket线程

热门问题