TCP服务器只能读取一条消息并停止

时间:2014-05-15 09:49:11

标签: python sockets tcp tcpserver

我在使这个TCP服务器正常运行时遇到一些麻烦...当我用netcat连接它时,我只能发送一条消息,然后服务器不显示其他发送消息。当我将client, addr = tcp_socket.accept()放在while循环之外时,我可以收到多条消息,但只能连接一次......

解决这些问题的最佳方法是什么?

代码

class TCP(threading.Thread):

    def __init__(self, host, port):
        self.port = port
        threading.Thread.__init__(self)

    def create_socket(self, port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('', port))
        sock.listen(5)
        return sock

    def listen(self, tcp_socket):
        while True:
            client, addr = tcp_socket.accept()
            print "Got connection from", addr
            data = client.recv(1024)
            if data:
                print "TCP", data

    def run(self):
        self.listen(self.create_socket(self.port))

1 个答案:

答案 0 :(得分:1)

这是一个工作示例服务器应用程序,它在循环外部有Socket.accept()

class (threading.Thread):
    def listenForClients(self, sock):
        while True:
            client, address = sock.accept()
            client.settimeout(5)
            threading.Thread( target = self.listenToClient, args = (client,address) ).start()

    def listenToClient(self, client, address):
        size = 1024
        while True:
            try:
                data = client.recv(size)
                if data:
                    response = "Got connection"
                    client.send(response)
                else:
                    raise error('Client disconnected')
            except:
                client.close()
                return False

    def __init__(self, host, port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((host, port))
        sock.listen(5)
        self.listenForClients(sock)

这为每个客户端使用一个线程,否则Socket.recv()阻塞,因此客户端必须轮流。