您现在的位置是:首页 > 手游攻略 > pythonsocket如何实现一个服务器对多个客户端进行交互?(python服务端对应多个客户端)

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

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

一,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':  

    

二,python socket 服务端

使用多线程,下面的代码,简单实现一个多线程的web服务器:


总结:以上内容就是宝宝游戏提供的pythonsocket如何实现一个服务器对多个客户端进行交互?(python服务端对应多个客户端)详细介绍,大家可以参考一下。