0

我正在学习 Python 上的多线程和套接字,但遇到了一个问题。我正在尝试创建一个服务器,该服务器将从同一台计算机上的多个客户端接收和打印数据。到目前为止,这是我的服务器代码:

import socket
import threading

def conn(HOST, PORT, BUFSIZE):
    serversock = RecvConnection(HOST, PORT) 
    serversock.listen(BUFSIZE)

class RecvConnection(object):

    def __init__(self,host, port, sock=None):
        if sock == None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

        self.sock.bind((host, port))    

    def listen(self, buffsize):
        self.sock.listen(5)
        clisock, (remhost, remport) = self.sock.accept()
        while 1:
            print clisock.recv(buffsize)

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024


threading.Thread(target=conn, args=(HOST, PORT, BUFSIZ,)).start()

问题是我的服务器似乎只处理了我的客户端文件的一个实例,因此它只显示我的客户端的第一个实例发送的数据。这是我的客户代码:

import socket
import threading

class CreateConnection(object):

    def __init__(self, sock=None):
        if sock is None:
            # Create a socket
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        # Connect to host, port
            self.sock.connect((host, port))

class Communication(CreateConnection):

    def sendMsg(self, msg):
        self.sock.send(msg)

HOST = 'localhost'
PORT = 21567

cltsock = Communication()
cltsock.connect(HOST, PORT)
while 1:
    msg = raw_input('> ')
    cltsock.sendMsg(msg)

任何人都可以帮助我实现这一目标吗?谢谢 !

4

1 回答 1

2

当服务器接受来自客户端的连接时,它应该启动一个线程来处理该连接,然后循环以等待下一个客户端。

[编辑]

这是我的意思的一个例子:

def listen(self, buffsize):
    self.sock.listen(5)

    while True:
        # Listen for a new client.
        clisock, (remhost, remport) = self.sock.accept()

        # Start listening to the new client.
        t = threading.Thread(target=self._handle_client, args=(clisock, buffsize))
        t.start()

def _handle_client(self, clisock, buffsize):
    while True:
        received = clisock.recv(buffsize)
        if not received:
            # The client has closed the connection.
            break

        print received
于 2012-06-29T19:31:22.133 回答