当TCPServer与ThreadingMixIn结合使用时,它会阻塞

时间:2014-08-03 04:57:19

标签: python multithreading python-multithreading

服务器端代码(tcp_server.py):

from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler

class Server(ThreadingMixIn, TCPServer):
    pass

class Handler(StreamRequestHandler):

    def handle(self):
        print 'got a connection from: ', self.request.getpeername()
        print self.rfile.read(1024)
        msg = 'hello'
        self.wfile.write(msg)

server = Server(('127.0.0.1', 8888), Handler)
server.serve_forever()

客户端代码(tcp_client.py):

from socket import *
import threading

def do_connection():
    s = socket(AF_INET, SOCK_STREAM)
    s.connect(('127.0.0.1', 8888))
    s.sendall('this is client')
    print s.recv(1024)

ts = []

for x in xrange(100):
    print x
    t = threading.Thread(target=do_connection())
    t.daemon = True
    ts.append(t)

for t in ts:
    t.start()

我跑了tcp_server.py,然后tcp_client.pytcp_client.py应该很快就会结束。但是,tcp_client.py似乎只运行一个线程并被阻止,tcp_server.py只有一个连接。当我中断tcp_client.py时,tcp_server.py收到一条消息this is client

我的代码中有错误吗?

2 个答案:

答案 0 :(得分:0)

这一行:

t = threading.Thread(target=do_connection())

应该是

t = threading.Thread(target=do_connection)

使用do_connection()时,最终会在主线程中执行do_connection,然后将该调用的返回值传递给Thread对象。您要做的是将do_connection函数对象传递给Thread,以便在调用Threaddo_connection对象可以在新线程中执行t.start

另请注意,同时启动100个线程以连接到您的服务器可能效果不佳。您可能需要考虑从较少的线程开始,并在知道事情正常工作后按照自己的方式工作。

答案 1 :(得分:0)

因为服务器被第一个请求阻止,我尝试将read(1024)更改为 server.py中的readline并添加' \ n'对于从客户端发出的内容,它 的工作原理。

似乎rfile.read(1024)将阻止进程如何,因此使用readline是正常的 或使用self.request.recv(1024)

server.py

from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler

class Server(ThreadingMixIn, TCPServer):
    pass

class Handler(StreamRequestHandler):

    def handle(self):
        print 'got a connection from: ', self.request.getpeername()
        print self.rfile.readline()
        #print self.request.recv(1024).strip()
        msg = 'hello'
        self.wfile.write(msg)


# Create the server, binding to localhost on port 9999
server = Server(("127.0.0.1", 8888), Handler)
server.serve_forever()

client.py

from socket import *
import threading

def do_connection():
    print "start"
    s = socket(AF_INET, SOCK_STREAM)
    s.connect(('127.0.0.1', 8888))
    s.sendall('this is client\n')
    print s.recv(1024)

ts = []

for x in xrange(100):
    print x
    t = threading.Thread(target=do_connection)
    ts.append(t)

for t in ts:
    print "start t"
    t.start()