我正在学习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)
任何人都可以帮助我实现这一目标吗? 谢谢!
答案 0 :(得分: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