<s> from autobahn . twisted . websocket import WebSocketServerFactory , WebSocketServerProtocol <EOL> class BroadcastServerProtocol ( WebSocketServerProtocol ) : <EOL> def onOpen ( self ) : <EOL> self . factory . register ( self ) <EOL> def onMessage ( self , payload , isBinary ) : <EOL> self . factory . broadcast ( payload , isBinary ) <EOL> def onClose ( self , wasClean , code , reason ) : <EOL> self . factory . unregister ( self ) <EOL> class BroadcastServerFactory ( WebSocketServerFactory ) : <EOL> """<STR_LIT>""" <EOL> protocol = BroadcastServerProtocol <EOL> def __init__ ( self , url ) : <EOL> WebSocketServerFactory . __init__ ( self , url , debug = False ) <EOL> self . clients = [ ] <EOL> def register ( self , client ) : <EOL> if client not in self . clients : <EOL> self . clients . append ( client ) <EOL> print ( "<STR_LIT>" . format ( client . peer ) ) <EOL> def unregister ( self , client ) : <EOL> if client in self . clients : <EOL> self . clients . remove ( client ) <EOL> print ( "<STR_LIT>" . format ( client . peer ) ) <EOL> def broadcast ( self , payload , isBinary ) : <EOL> for c in self . clients : <EOL> c . sendMessage ( payload , isBinary ) <EOL> print ( "<STR_LIT>" . format ( len ( self . clients ) ) ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> import sys <EOL> from twisted . python import log <EOL> from twisted . internet import reactor <EOL> log . startLogging ( sys . stdout ) <EOL> factory = BroadcastServerFactory ( u"<STR_LIT>" ) <EOL> reactor . listenTCP ( <NUM_LIT> , factory ) <EOL> reactor . run ( ) </s>
