Beispiel #1
0
class LiberateFactory(protocol.ServerFactory):
    '''协议工厂'''
    protocol = WebSocketLiberateProtocol

    # protocol = LiberateProtocol

    def __init__(self, dataprotocl=DataPackProtoc()):
        '''初始化
        '''
        self.service = None
        self.connmanager = ConnectionManager()
        self.dataprotocl = dataprotocl

    def setDataProtocl(self, dataprotocl):
        '''
        '''
        self.dataprotocl = dataprotocl

    def doConnectionMade(self, conn):
        '''当连接建立时的处理'''
        pass

    def doConnectionLost(self, conn):
        '''连接断开时的处理'''
        pass

    def addServiceChannel(self, service):
        '''添加服务通道'''
        self.service = service

    def doDataReceived(self, conn, commandID, data):
        '''数据到达时的处理'''
        defer_tool = self.service.callTarget(commandID, conn, data)
        return defer_tool

    def produceResult(self, command, response):
        '''产生客户端需要的最终结果
        @param response: str 分布式客户端获取的结果
        '''
        return self.dataprotocl.pack(command, response)

    def loseConnection(self, connID):
        """主动端口与客户端的连接
        """
        self.connmanager.loseConnection(connID)

    def pushObject(self, topicID, msg, sendList):
        '''服务端向客户端推消息
        @param topicID: int 消息的主题id号
        @param msg: 消息的类容,protobuf结构类型
        @param sendList: 推向的目标列表(客户端id 列表)
        '''
        self.connmanager.pushObject(topicID, msg, sendList)
Beispiel #2
0
class LiberateFactory(protocol.ServerFactory):
    """协议工厂"""

    protocol = LiberateProtocol

    def __init__(self,dataprotocl=DataPackProtoc()):
        """初始化
        """
        self.service = None
        self.connmanager = ConnectionManager()
        self.dataprotocl = dataprotocl

    def setDataProtocl(self,dataprotocl):
        """
        """
        self.dataprotocl = dataprotocl

    def doConnectionMade(self,conn):
        """当连接建立时的处理"""
        pass

    def doConnectionLost(self,conn):
        """连接断开时的处理"""
        pass

    def addServiceChannel(self,service):
        """添加服务通道"""
        self.service = service

    def doDataReceived(self,conn,commandID,data):
        """数据到达时的处理"""
        defer_tool = self.service.callTarget(commandID,conn,data)
        return defer_tool

    def produceResult(self,response,command):
        """产生客户端需要的最终结果
        @param response: str 分布式客户端获取的结果
        """
        return self.dataprotocl.pack(response,command)

    def loseConnection(self,connID):
        """主动端口与客户端的连接
        """
        self.connmanager.loseConnection(connID)

    def pushObject(self,topicID , msg, sendList):
        """服务端向客户端推消息
        @param topicID: int 消息的主题id号
        @param msg: 消息的类容,protobuf结构类型
        @param sendList: 推向的目标列表(客户端id 列表)
        """
        self.connmanager.pushObject(topicID, msg, sendList)
 def __init__(self, dataprotocol=DataPackProtocol()):
     '''初始化
     '''
     self.service = None
     self.connmanager = ConnectionManager()
     self.dataprotocol = dataprotocol
     self.codec = None
Beispiel #4
0
class GxgServerFactory(WebSocketServerFactory):
    protocol = GxgServerProtocol

    def __init__(self, wsuri):
        WebSocketServerFactory.__init__(self, wsuri)
        self.connmanager = ConnectionManager()
        self.gamemanger_A = Gamemanger()
        self.tick()

    def tick(self):
        for sendlist, msg in self.gamemanger_A.movebroad("move"):
            if msg["player"] != None:
                self.broadcast(json.dumps(msg).encode('utf8'), sendlist)
        reactor.callLater(0.1, self.tick)

    def broadcast(self, msg, sendlist):
        # print("broadcasting prepared message '{}' ..".format(msg))
        preparedMsg = self.prepareMessage(msg)
        self.connmanager.pushObjectbyconnIDlist(preparedMsg, sendlist)
Beispiel #5
0
 def __init__(self, dataprotocl=DataPackProtoc()):
     """初始化
     """
     self.service = None
     self.connmanager = ConnectionManager()
     self.dataprotocl = dataprotocl
class LiberateFactory(protocol.ServerFactory):
    '''协议工厂'''
    
    protocol = LiberateProtocol
    
    def __init__(self, dataprotocol=DataPackProtocol()):
        '''初始化
        '''
        self.service = None
        self.connmanager = ConnectionManager()
        self.dataprotocol = dataprotocol
        self.codec = None
        
    def setDataProtocol(self, dataprotocol):
        '''
        '''
        self.dataprotocol = dataprotocol
        
    def doConnectionMade(self, conn):
        '''当连接建立时的处理'''
        pass
    
    def doConnectionLost(self, conn):
        '''连接断开时的处理'''
        pass
    
    def addServiceChannel(self, service):
        '''添加服务通道'''
        self.service = service
    
    def doDataReceived(self, conn, commandID, data, encryptAlgorithm = 0):
        # verify and decode body
        decoded = data
        if self.codec:
            if not self.codec.verifyAlgorithm(commandID, encryptAlgorithm):
                log.msg('suspicious packet encrypt algorithm')
                return None
            decoded = self.codec.decode(data, encryptAlgorithm)

        # deliver
        defer_tool = self.service.callTarget(commandID, conn, decoded)
        return defer_tool
    
    def produceResult(self, command, response):
        '''
        generate packet can be directly sent through socket
        @param command: command id
        @param response: body string
        @return: binary packet to be sent
        '''

        # encode body
        encoded = response
        alg = 0
        if self.codec:
            alg = self.codec.selectAlgorithm(command, response)
            encoded = self.codec.encode(response, alg)

        return self.dataprotocol.pack(command, encoded, encryptAlgorithm = alg)
    
    def loseConnection(self, connID):
        """主动端口与客户端的连接
        """
        self.connmanager.loseConnection(connID)
    
    def pushObject(self, command, msg, sendList=[]):
        '''
        server push a message to all clients, with given command
        @param command: command id
        @param msg: json body
        @param sendList a list of client connection id to where the message will be pushed to, if
            empty, push to all clients
        '''
        self.connmanager.pushObject(command, msg, sendList)
Beispiel #7
0
 def __init__(self,dataprotocl=DataPackProtoc()):
     """初始化
     """
     self.service = None
     self.connmanager = ConnectionManager()
     self.dataprotocl = dataprotocl
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from manager import ConnectionManager

manager = ConnectionManager()
app = FastAPI()
templates = Jinja2Templates(directory="./templates")

@app.get("/")
async def index(request: Request, response_class=HTMLResponse):
    return templates.TemplateResponse('index.html', {'request': request})

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")
Beispiel #9
0
 def __init__(self, wsuri):
     WebSocketServerFactory.__init__(self, wsuri)
     self.connmanager = ConnectionManager()
     self.gamemanger_A = Gamemanger()
     self.tick()