python socketserver连接数量限制,Python SocketServer:发送到多个客户端?

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.

解决方案

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:

from __future__ import print_function

import asyncore

import collections

import logging

import socket

MAX_MESSAGE_LENGTH = 1024

class RemoteClient(asyncore.dispatcher):

"""Wraps a remote client socket."""

def __init__(self, host, socket, address):

asyncore.dispatcher.__init__(self, socket)

self.host = host

self.outbox = collections.deque()

def say(self, message):

self.outbox.append(message)

def handle_read(self):

client_message = self.recv(MAX_MESSAGE_LENGTH)

self.host.broadcast(client_message)

def handle_write(self):

if not self.outbox:

return

message = self.outbox.popleft()

if len(message) > MAX_MESSAGE_LENGTH:

raise ValueError('Message too long')

self.send(message)

class Host(asyncore.dispatcher):

log = logging.getLogger('Host')

def __init__(self, address=('localhost', 0)):

asyncore.dispatcher.__init__(self)

self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

self.bind(address)

self.listen(1)

self.remote_clients = []

def handle_accept(self):

socket, addr = self.accept() # For the remote client.

self.log.info('Accepted client at %s', addr)

self.remote_clients.append(RemoteClient(self, socket, addr))

def handle_read(self):

self.log.info('Received message: %s', self.read())

def broadcast(self, message):

self.log.info('Broadcasting message: %s', message)

for remote_client in self.remote_clients:

remote_client.say(message)

class Client(asyncore.dispatcher):

def __init__(self, host_address, name):

asyncore.dispatcher.__init__(self)

self.log = logging.getLogger('Client (%7s)' % name)

self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

self.name = name

self.log.info('Connecting to host at %s', host_address)

self.connect(host_address)

self.outbox = collections.deque()

def say(self, message):

self.outbox.append(message)

self.log.info('Enqueued message: %s', message)

def handle_write(self):

if not self.outbox:

return

message = self.outbox.popleft()

if len(message) > MAX_MESSAGE_LENGTH:

raise ValueError('Message too long')

self.send(message)

def handle_read(self):

message = self.recv(MAX_MESSAGE_LENGTH)

self.log.info('Received message: %s', message)

if __name__ == '__main__':

logging.basicConfig(level=logging.INFO)

logging.info('Creating host')

host = Host()

logging.info('Creating clients')

alice = Client(host.getsockname(), 'Alice')

bob = Client(host.getsockname(), 'Bob')

alice.say('Hello, everybody!')

logging.info('Looping')

asyncore.loop()

Which results in the following output:

INFO:root:Creating host

INFO:root:Creating clients

INFO:Client ( Alice):Connecting to host at ('127.0.0.1', 51117)

INFO:Client ( Bob):Connecting to host at ('127.0.0.1', 51117)

INFO:Client ( Alice):Enqueued message: Hello, everybody!

INFO:root:Looping

INFO:Host:Accepted client at ('127.0.0.1', 55628)

INFO:Host:Accepted client at ('127.0.0.1', 55629)

INFO:Host:Broadcasting message: Hello, everybody!

INFO:Client ( Alice):Received message: Hello, everybody!

INFO:Client ( Bob):Received message: Hello, everybody!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值