Python SocketServer:发送到多个客户端?
好吧,我正在尝试使用 SocketServer 构建一个小型 python 程序,该程序应该将其收到的消息发送给所有连接的客户端。我陷入困境,我不知道如何在服务器端存储客户端,也不知道如何发送到多个客户端。哦,每当有超过 1 个客户端连接时,每次客户端发送超过一条消息时,我的程序都会失败...
到目前为止,这是我的代码:
print str(self.client_address[0])+' connected.'
def handle(self):
new=1
for client in clients:
if client==self.request:
new=0
if new==1:
clients.append(self.request)
for client in clients:
data=self.request.recv(1024)
client.send(data)
class Host:
def __init__(self):
self.address = ('localhost', 0)
self.server = SocketServer.TCPServer(self.address, EchoRequestHandler)
ip, port = self.server.server_address
self.t = threading.Thread(target=self.server.serve_forever)
self.t.setDaemon(True)
self.t.start()
print ''
print 'Hosted with IP: '+ip+' and port: '+str(port)+'. Clients can now connect.'
print ''
def close(self):
self.server.socket.close()
class Client:
name=''
ip=''
port=0
def __init__(self,ip,port,name):
self.name=name
self.hostIp=ip
self.hostPort=port
self.s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((self.hostIp, self.hostPort))
def reco(self):
self.s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((self.hostIp, self.hostPort))
def nick(self,newName):
self.name=newName
def send(self,message):
message=self.name+' : '+message
len_sent=self.s.send(message)
response=self.s.recv(len_sent)
print response
self.reco()
def close(self):
self.s.close()
显然我不知道我在做什么,所以任何帮助都会很棒。< br> 提前致谢!
编辑:我在 Windows Vista 上使用 Python 2.7。
Well, I'm trying to build a small python prgram with a SocketServer that is supposed to send messages it receives to all connected clients. I'm stuck, I don't know how to store clients on the serverside, and I don't know how to send to multiple clients. Oh and, my program fails everytime more then 1 client connects, and everytime a client sends more then one message...
Here's my code until now:
print str(self.client_address[0])+' connected.'
def handle(self):
new=1
for client in clients:
if client==self.request:
new=0
if new==1:
clients.append(self.request)
for client in clients:
data=self.request.recv(1024)
client.send(data)
class Host:
def __init__(self):
self.address = ('localhost', 0)
self.server = SocketServer.TCPServer(self.address, EchoRequestHandler)
ip, port = self.server.server_address
self.t = threading.Thread(target=self.server.serve_forever)
self.t.setDaemon(True)
self.t.start()
print ''
print 'Hosted with IP: '+ip+' and port: '+str(port)+'. Clients can now connect.'
print ''
def close(self):
self.server.socket.close()
class Client:
name=''
ip=''
port=0
def __init__(self,ip,port,name):
self.name=name
self.hostIp=ip
self.hostPort=port
self.s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((self.hostIp, self.hostPort))
def reco(self):
self.s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.connect((self.hostIp, self.hostPort))
def nick(self,newName):
self.name=newName
def send(self,message):
message=self.name+' : '+message
len_sent=self.s.send(message)
response=self.s.recv(len_sent)
print response
self.reco()
def close(self):
self.s.close()
Obviously I have no idea what I'm doing, so any help would be great.
Thanks in advance!
Edit: I'm using Python 2.7 on Windows Vista.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想在此处查看 asyncore 。您在客户端调用的套接字操作是阻塞的(直到收到一些数据或发生超时才返回),这使得很难侦听从主机发送的消息并让客户端实例将数据排入队列以发送同时。 asyncore 应该将基于超时的轮询循环从您手中抽象出来。
这是一个代码“示例”——如果有任何不清楚的地方请告诉我:
这会产生以下输出:
You want to look at asyncore here. The socket operations you're calling on the client side are blocking (don't return until some data is received or a timeout occurs) which makes it hard to listen for messages sent from the host and let the client instances enqueue data to send at the same time. asyncore is supposed to abstract the timeout-based polling loop away from you.
Here's a code "sample" -- let me know if anything is unclear:
Which results in the following output:
您可以使用
socketserver
将消息广播到所有连接的客户。但是,该功能并未内置到代码中,需要通过扩展一些已提供的类来实现。在以下示例中,这是使用 ThreadingTCPServer 和 StreamRequestHandler 类实现的。它们提供了构建的基础,但仍然需要进行一些修改才能实现您想要完成的任务。文档应该帮助解释每个函数、类和方法为了完成工作而试图做什么。服务器
当然,您还需要一个可以与服务器通信并使用与服务器相同的协议的客户端。由于这是 Python,因此决定使用
pickle
< /a> 模块以促进服务器和客户端之间的数据传输。可以使用其他数据传输方法(例如 JSON、XML 等),但能够 pickle 和 unpickle 数据足以满足该程序的需求。文档再次包含在内,因此弄清楚发生了什么应该不会太困难。请注意,服务器命令可能会中断用户数据输入。客户端
You can use
socketserver
to broadcast messages to all connected clients. However, the ability is not built into the code and will need to be implemented by extending some of the classes already provided. In the following example, this is implemented using theThreadingTCPServer
andStreamRequestHandler
classes. They provide a foundation on which to build but still require some modifications to allow what you are trying to accomplish. The documentation should help explain what each function, class, and method are trying to do in order to get the job done.Server
Of course, you also need a client that can communicate with your server and use the same protocol the server speaks. Since this is Python, the decision was made to utilize the
pickle
module to facilitate data transfer among server and clients. Other data transfer methods could have been used (such as JSON, XML, et cetera), but being able to pickle and unpickle data serves the needs of this program well enough. Documentation is included yet again, so it should not be too difficult to figure out what is going on. Note that server commands can interrupt user data entry.Client
为什么使用SocketServer?简单的客户端无法满足您的需求?
why use SocketServer? a simple client doesn't meet your needs?
要同时获取多个客户端,您必须添加 SocketServer.ForkingMixIn 或 ThreadingMixIn 。
To take multiple clients simultaneously, you will have to add
SocketServer.ForkingMixIn
orThreadingMixIn
.