/**
 * session class. The front-end server represents the client connection, and the back-end server is a copy of some data
 */ import Application from "../application" ; import { I_clientSocket , sessionCopyJson } from "../util/interfaceDefine" ; let app ; export function initSessionApp ( _app ) { app = _app ; } export class Session { uid : number = 0 ; private sid : string = "" ; private settings : { [ key ] : any ; } = { } ; private settingsLocal : { [ key ] : any ; } = { } ; sessionBuf : Buffer = null as any ; socket : I_clientSocket = null as any ; constructor ( sid = "" ) { this . sid = sid ; this . resetBuf ( ) ; } private resetBuf ( ) { if ( app . frontend ) { let tmpBuf = Buffer . from ( JSON . stringify ( { "uid" : this . uid , "sid" : this . sid , "settings" : this . settings } ) ) ; this . sessionBuf = Buffer . alloc ( tmpBuf . length ) . fill ( tmpBuf ) ; } } /**
     * Binding session [Note: Front-end call]
     */ bind ( _uid ) { if ( ! app . frontend || ! this . socket ) { return false ; } if ( app . clients [ _uid ] ) { return false ; } app . clients [ _uid ] = this . socket ; this . uid = _uid ; this . resetBuf ( ) ; return true ; } set ( _settings ) { for ( let f in _settings ) { this . settings [ f ] = _settings [ f ] ; } this . resetBuf ( ) ; } get ( key ) { return this . settings [ key ] ; } delete ( keys ) { for ( let one of keys ) { delete this . settings [ one ] ; } this . resetBuf ( ) ; } setLocal ( key , value ) { this . settingsLocal [ key ] = value ; } getLocal ( key ) { return this . settingsLocal [ key ] ; } deleteLocal ( key ) { delete this . settingsLocal [ key ] ; } /**
     * Set up all sessions
     */ setAll ( _session ) { this . uid = _session . uid ; this . sid = _session . sid ; this . settings = _session . settings ; } /**
     * Close the connection [Note: Front-end call]
     */ close ( ) { if ( app . frontend && this . socket ) { this . socket . close ( ) ; } } /**
     * Push the back-end session to the front-end [Note: back-end call]
     */ apply ( ) { if ( ! app . frontend ) { app . backendServer . sendSession ( this . sid , Buffer . from ( JSON . stringify ( { "uid" : this . uid , "settings" : this . settings } ) ) ) ; } } /**
     * After the back-end calls apply, the processing received by the front-end
     */ applySession ( settings ) { this . settings = settings ; this . resetBuf ( ) ; } /**
     * Get ip
     */ getIp ( ) { if ( this . socket ) { return this . socket . remoteAddress ; } else { return "" ; } } /** Send msg to client */ send ( cmd , msg ) { if ( ! app . frontend || ! this . socket ) { return ; } if ( msg === undefined ) { msg = null ; } let msgBuf = app . protoEncode ( cmd , msg ) ; this . socket . send ( msgBuf ) ; } }