您必须在不同的线程中运行它或使用内置的 asyncore 库。大多数库都会在你不知道的情况下使用线程,或者它将依赖于 Python 的标准部分 asyncore。
这是线程和异步的组合:
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import asyncore, socket
from threading import *
from time import sleep
from os import _exit
from logger import * # <- Non-standard library containing a log function
from config import * # <- Non-standard library containing settings such as "server"
class logDispatcher(Thread, asyncore.dispatcher):
def __init__(self, config=None):
self.inbuffer = ''
self.buffer = ''
self.lockedbuffer = False
self.is_writable = False
self.is_connected = False
self.exit = False
self.initated = False
asyncore.dispatcher.__init__(self)
Thread.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.connect((server, server_port))
except:
log('Could not connect to ' + server, 'LOG_SOCK')
return None
self.start()
def handle_connect_event(self):
self.is_connected = True
def handle_connect(self):
self.is_connected = True
log('Connected to ' + str(server), 'LOG_SOCK')
def handle_close(self):
self.is_connected = False
self.close()
def handle_read(self):
data = self.recv(8192)
while self.lockedbuffer:
sleep(0.01)
self.inbuffer += data
def handle_write(self):
while self.is_writable:
sent = self.send(self.buffer)
sleep(1)
self.buffer = self.buffer[sent:]
if len(self.buffer) <= 0:
self.is_writable = False
sleep(0.01)
def _send(self, what):
self.buffer += what + '\r\n'
self.is_writable = True
def run(self):
self._send('GET / HTTP/1.1\r\n')
while 1:
logDispatcher() # <- Initate one for each request.
asyncore.loop(0.1)
log('All threads are done, next loop in 10', 'CORE')
sleep(10)
或者你可以简单地做一个线程来完成这项工作然后死掉。
from threading import *
class worker(Thread):
def __init__(self, host, postdata)
Thread.__init__(self)
self.host = host
self.postdata = postdata
self.start()
def run(self):
sock.send(self.postdata) #Pseudo, create the socket!
for data in postDataObjects:
worker('example.com', data)
如果您需要限制线程数(如果您发送的帖子超过 5k 条左右,可能会对系统造成负担),只需执行 awhile len(enumerate()) > 1000: sleep(0.1)
并让 looper 对象等待几个线程消失。