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