コード例 #1
0
ファイル: server.py プロジェクト: leecrest/wafer
 def Start(self):
     if self.m_State == SERVER_STATE_NONE:
         log.Fatal("server need init first")
         return
     elif self.m_State == SERVER_STATE_START:
         log.Fatal("server(%s) already started" % self.m_Name)
         return
     log.Info("Server(%s) start now" % self.m_Name)
     reactor.callLater(1, self.ServerStart)
     reactor.run()
コード例 #2
0
ファイル: packet.py プロジェクト: leecrest/wafer
def UnpackNet(iConnID, sBuff):
    if len(sBuff) <= PACKET_HEAD_LEN:
        return
    #解析网络包
    try:
        iCrypt, iPackLen = struct.unpack("!BH", sBuff[:PACKET_HEAD_LEN])
    except Exception, err:
        log.Fatal(str(err))
        return
コード例 #3
0
ファイル: packet.py プロジェクト: leecrest/wafer
 def Read(self, sType, bList=False):
     if sType == "string":
         return self.__ReadString__(bList)
     elif sType in BASIC_TYPE:
         return self.__ReadNumber__(sType, bList)
     elif sType in g_CustomType:
         return self.__ReadCustom__(sType, bList)
     else:
         log.Fatal("[ReadPack]type=%s is not supported" % sType)
コード例 #4
0
ファイル: server.py プロジェクト: leecrest/wafer
 def Stop(self):
     if self.m_State != SERVER_STATE_START:
         log.Fatal("server(%s) has not started, cannot stop!" % self.m_Name)
         return
     self.m_State = SERVER_STATE_STOP
     log.Info("server(%s) stopped!" % self.m_Name)
     cbFunc = self.m_Handler.get("ServerStop", None)
     if cbFunc:
         cbFunc(self)
     reactor.stop()
コード例 #5
0
ファイル: packet.py プロジェクト: leecrest/wafer
 def Write(self, sType, sValue, bList=False):
     #print "<<<Write>>>", sType, sValue, bList
     if not self.m_ProtoID:
         return
     if sType == "string":
         return self.__WriteString__(sValue, bList)
     elif sType in BASIC_TYPE:
         return self.__WriteNumber__(sType, sValue, bList)
     elif sType in g_CustomType:
         return self.__WriteCustom__(sType, sValue, bList)
     else:
         log.Fatal("[WritePack]type=%s is not supported" % sType)
コード例 #6
0
ファイル: packet.py プロジェクト: leecrest/wafer
def PackProto(sProtoName, dProtocol):
    """
	压包,将源数据按照iIndex的协议格式进行压包
	:param sProtoName:协议名称
	:param dProtocol:
	:return:
	"""
    #准备
    iProtoID = g_Name2ID[sProtoName]
    g_ProtocolWriter.__init__(iProtoID)
    #按照协议进行打包
    dProtoCfg = g_ProtoCfg[iProtoID]
    if not dProtoCfg:
        log.Fatal("[PackNet] protocol %d is not supported" % iProtoID)
        return
    for tArg in dProtoCfg["args"]:
        sName, sType = tArg[0], tArg[1]
        if not sName in dProtocol:
            log.Fatal("[PackNet] protocol %d need (%s)" % (iProtoID, sName))
            raise "[PackNet] protocol %d need (%s)" % (iProtoID, sName)
        bList = False
        if len(tArg) >= 3:
            bList = tArg[2]
        if not bList:
            sValue = dProtocol[sName]
            if not g_ProtocolWriter.Write(sType, sValue):
                log.Fatal(
                    "[PacketNet] protocol %d write failed at (%s,%s,%s)" %
                    (iProtoID, sName, sType, sValue))
                return
        else:
            sValueList = dProtocol[sName]
            g_ProtocolWriter.Write("uint8", len(sValueList))
            for sValue in sValueList:
                if not g_ProtocolWriter.Write(sType, sValue):
                    log.Fatal(
                        "[PacketNet] protocol %d write failed at (%s,%s,%s)" %
                        (iProtoID, sName, sType, sValue))
                    return
    return g_ProtocolWriter.Pack()
コード例 #7
0
ファイル: packet.py プロジェクト: leecrest/wafer
def UnpackMetaData(iProtoID, sMetaData):
    dProtoCfg = g_ProtoCfg.get(iProtoID, None)
    if not dProtoCfg:
        return
    #将数据加载到读内存中
    g_ProtocolReader.__init__(sMetaData)
    #按照指定的协议格式进行解包
    sProtoName = dProtoCfg["name"]
    if not dProtoCfg:
        log.Fatal("[UnpackNet] protocol %d is not supported" % iProtoID)
        return
    dProtocol = {}
    for tArg in dProtoCfg["args"]:
        sArgName, sArgType = tArg[0], tArg[1]
        bList = False
        if len(tArg) >= 3:
            bList = tArg[2]
        sArgValue = g_ProtocolReader.Read(sArgType, bList)
        if sArgValue is None:
            log.Fatal("[UnpackNet] protocol %d is error at (%s, %s)" %
                      (iProtoID, sArgName, sArgType))
            return
        dProtocol[sArgName] = sArgValue
    return sProtoName, dProtocol
コード例 #8
0
 def DataHandleCoroutine(self):
     iConnID = self.GetConnID()
     #获取协议头的长度
     while True:
         data = yield
         self.m_Buff += data
         while self.m_Buff.__len__() >= packet.PACKET_HEAD_LEN:
             PackInfo = packet.UnpackNet(iConnID, self.m_Buff)
             if not PackInfo:
                 log.Fatal("illegal data package -- [%s]" % PackInfo)
                 self.transport.loseConnection()
                 break
             sProtoName, iPackLen, dProtoData = PackInfo
             self.m_Buff = self.m_Buff[packet.PACKET_HEAD_LEN + iPackLen:]
             log.Info("recv %s/%d from %d" %
                      (sProtoName, iPackLen, iConnID))
             self.factory.DataReceived(self.GetConnID(), sProtoName,
                                       dProtoData)
コード例 #9
0
ファイル: packet.py プロジェクト: leecrest/wafer
        return
    if len(sBuff) < PACKET_HEAD_LEN + iPackLen:
        return
    #包体,协议数据部分
    sProtoBuff = sBuff[PACKET_HEAD_LEN:PACKET_HEAD_LEN + iPackLen]
    #解密
    if iCrypt:
        sProtoBuff = Decrypt(iConnID, sProtoBuff)
    #判断数据有效性
    if not sProtoBuff or len(sProtoBuff) <= PROTOCOL_HEAD_LEN:
        return
    try:
        iProtoID, iProtoLen = struct.unpack("HH",
                                            sProtoBuff[:PROTOCOL_HEAD_LEN])
    except Exception, err:
        log.Fatal(str(err))
        return
    if len(sProtoBuff) < PROTOCOL_HEAD_LEN + iProtoLen:
        return
    sMetaData = sProtoBuff[PROTOCOL_HEAD_LEN:PROTOCOL_HEAD_LEN + iProtoLen]
    dProtoCfg = g_ProtoCfg.get(iProtoID, None)
    if not dProtoCfg:
        #本服务器没有此协议的定义,不解包
        return "default", iPackLen, {"ProtoID": iProtoID, "Data": sMetaData}

    #将数据加载到读内存中
    g_ProtocolReader.__init__(sMetaData)
    #按照指定的协议格式进行解包
    sProtoName = dProtoCfg["name"]
    if not dProtoCfg:
        log.Fatal("[UnpackNet] protocol %d is not supported" % iProtoID)
コード例 #10
0
ファイル: server.py プロジェクト: leecrest/wafer
    def InitConfig(self, sName, dConfig):
        if "name" in dConfig:
            sName = dConfig["name"]
        self.m_Name = sName
        #服务器配置
        self.m_bFrontEnd = dConfig.get("frontend", False)
        #执行根目录
        sPath = dConfig.get("path", None)
        if sPath:
            import os, sys
            os.chdir(sPath)
            sys.path.insert(0, sPath)
            log.Info("server(%s) change root path to (%s)" %
                     (self.m_Name, sPath))

        #日志路径
        self.m_LogPath = dConfig.get("log", "./")
        log.InitLog(self.m_LogPath)

        #初始化net,目前仅有前端服务器支持net参数
        if self.m_bFrontEnd:
            dNetCfg = dConfig.get("net", None)
            if not dNetCfg:
                log.Fatal("server(%s) need config about network" % self.m_Name)
                return
            sNetType = dNetCfg["type"].lower()
            if sNetType == NET_TYPE_TCP:
                import wafer.tcp
                self.m_NetType = NET_TYPE_TCP
                self.m_Modules["net"] = wafer.tcp.CreateServer(
                    self.m_Name, dNetCfg["host"], dNetCfg["port"])
                log.Info("%s(%s) listen at %d" %
                         (self.m_Name, sNetType, dNetCfg["port"]))
            elif sNetType == NET_TYPE_HTTP:
                self.m_NetType = NET_TYPE_HTTP
            elif sNetType == NET_TYPE_WEBSOCKET:
                self.m_NetType = NET_TYPE_WEBSOCKET

        #初始化web
        dWebCfg = dConfig.get("web", None)
        if dWebCfg:
            import wafer.web
            sHost = dWebCfg.get("url", "127.0.0.1")
            self.m_Modules["web"] = wafer.web.CreateWebServer(
                sHost, dWebCfg["port"])
            log.Info("server(%s) listen web port at %s:%d" %
                     (self.m_Name, sHost, dWebCfg["port"]))

        #RPC初始化
        dRpcList = dConfig.get("rpc", [])
        if dRpcList:
            import wafer.rpc
            for dRpcCfg in dRpcList:
                sRpcName = dRpcCfg["name"]
                if dRpcCfg.get("server", False):
                    oRpcNode = wafer.rpc.CreateRpcServer(
                        sRpcName, dRpcCfg["port"])
                    log.Info("%s(rpc) listen at %d" %
                             (sRpcName, dRpcCfg["port"]))
                else:
                    tAddress = (dRpcCfg["host"], dRpcCfg["port"])
                    oRpcNode = wafer.rpc.CreateRpcClient(
                        self.m_Name, sRpcName, tAddress)
                    log.Info("%s create rpc_client to %s" %
                             (self.m_Name, sRpcName))
                self.m_RpcDict[sRpcName] = oRpcNode

        #redis
        dCfg = dConfig.get("redis", None)
        if dCfg:
            import redis
            self.m_Modules["redis"] = redis.Redis(
                host=dCfg.get("host", "localhost"),
                port=dCfg.get("port", 6379),
                db=dCfg.get("db", 0),
            )
            log.Info("server(%s) start redis" % self.m_Name)

        #每个进程配置init选项,启动时将加载此文件
        sInitFile = dConfig.get("init", None)
        mod = self.Import(sInitFile)
        if hasattr(mod, "ServerStart"):
            self.m_Handler["ServerStart"] = mod.ServerStart
        if hasattr(mod, "ServerStop"):
            self.m_Handler["ServerStop"] = mod.ServerStop
        if self.m_NetType == NET_TYPE_TCP:
            oNetNode = self.m_Modules.get("net", None)
            if oNetNode:
                if hasattr(mod, "ConnectionLost"):
                    oNetNode.GetService().SetCallback("__OnConnectionLost",
                                                      mod.ConnectionLost)
                if hasattr(mod, "ConnectionMade"):
                    oNetNode.GetService().SetCallback("__OnConnectionMade",
                                                      mod.ConnectionMade)
        self.m_State = SERVER_STATE_INIT
        log.Info("server(%s) init success!" % self.m_Name)
コード例 #11
0
def DefferedErrorHandle(e):
    """延迟对象的错误处理"""
    log.Fatal(str(e))
    return