专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

pythonsocket如何实现一个服务器对多个客户端进行交互_CSS学习

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/3/4 5:21:37       共计:3634 浏览

pythonsocket如何实现一个服务器对多个客户端进行交互?

用twisted,用工厂管理连接,每个连接建立transport. 使用简单方便!参看下面代码:

# Copyright (c) The PyAMF Project.

# See LICENSE.txt for details.

"""

Example socket server using Twisted.

@see: U{Documentation for this example<http://pyamf.org/tutorials/actionscript/socket.html>}

@since: 0.1

"""

try:

import twisted

except ImportError:

print "This examples requires the Twisted framework. Download it from http://twistedmatrix.com"

raise SystemExit

from twisted.internet.protocol import Protocol, Factory

from twisted.internet import reactor

from datetime import datetime

import pyamf

class TimerProtocol(Protocol):

interval = 1.0 # 客户端链接到server后,server往客户端发送时间的间隔

encoding = pyamf.AMF3

timeout = 20 #客户端链接到server后多少时间不操作就断开链接的timeout

def __init__(self):

self.started = False

#设置编码器

self.encoder = pyamf.get_encoder(self.encoding)、

#设置server端将数据编码成amf后存放的缓存地址

self.stream = self.encoder.stream

def connectionLost(self, reason):

Protocol.connectionLost(self, reason)

print "locst connection:",reason

#客户端没断开一个链接,总连接数-1

self.factory.number_of_connections -= 1

print "number_of_connections:",self.factory.number_of_connections

def connectionMade(self):

#如果服务器连接数超过最大连接数,拒绝新链接建立

if self.factory.number_of_connections >= self.factory.max_connections:

self.transport.write('Too many connections, try again later')

self.transport.loseConnection()

return

#总连接数+1

self.factory.number_of_connections += 1

self.timeout_deferred = reactor.callLater(TimerProtocol.timeout, self.transport.loseConnection)

def dataReceived(self, data):

#去除server收到client数据两端的空格

data = data.strip()

#如果收到的是'start'命令

if data == 'start':

# start sending a date object that contains the current time

if not self.started:

self.start()

elif data == 'stop':

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:移动积分怎么兑QQ会员_CSS学习 | ·下一条:孩子最喜欢看哪些绘本_CSS学习

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有