コード例 #1
0
ファイル: test.py プロジェクト: EricSchles/AutobahnPython
def test_server(wsuri, wsuri2 = None):

   dealer = Dealer()

   if wsuri2 is None:
      calculator = Calculator()
      dealer.register("http://myapp.com/", calculator)


   broker = Broker()

   class MyPubSubServerProtocol(WampServerProtocol):

      def onSessionOpen(self):
         self.setBroker(broker)
         self.setDealer(dealer)

   wampFactory = WampServerFactory(wsuri)
   wampFactory.protocol = MyPubSubServerProtocol
   listenWS(wampFactory)

   if wsuri2:
      class MyPubSubClientProtocol(WampClientProtocol):

         def onSessionOpen(self):
            self.setBroker(broker)
            self.setDealer(dealer)

      factory = WampClientFactory(wsuri2)
      factory.protocol = MyPubSubClientProtocol
      connectWS(factory)
コード例 #2
0
def main():

    server_url = "ws://%s:%d" % (SERVER, WS_PORT)

    if DEBUG:
        log.startLogging(sys.stdout)

    # WebSocket Factory for communicating with browser
    ws_factory = MSP430SocketServerFactory(server_url,
                                           debug=DEBUG,
                                           debugCodePaths=DEBUG)
    ws_factory.protocol = MSP430ServerProtocol

    # TCP Server for communicating with MSP430 and Django Application
    web_factory = protocol.Factory()
    web_factory.protocol = WebServerProtocol

    if DEBUG:
        web_factory.protocol.debug = True

    # Need to know how to communicate both directions
    web_factory.ws_factory = ws_factory
    ws_factory.web_factory = web_factory

    listenWS(ws_factory)
    reactor.listenTCP(HTTP_PORT, web_factory)

    reactor.run()
コード例 #3
0
ファイル: sockServer.py プロジェクト: dpmack/Project1536
def main(curDir):
    class WhiteboardServerProtocol(WebSocketServerProtocol):
        def onConnect(self, connectionRequest):
            whiteboard.addClient(self)
            return None

        def onMessage(self, msg, binary):
            whiteboard.processMessage(self, msg)

    os.chdir(curDir)

    #log.startLogging(sys.stdout)
    debugWS = False
    debugWhiteboard = False
    whiteboard = WhiteboardServer(debugWhiteboard)

    factory = WebSocketServerFactory("ws://localhost:9000",
                                     debug=debugWS,
                                     debugCodePaths=debugWS)

    factory.protocol = WhiteboardServerProtocol
    #factory.setProtocolOptions(allowHixie76 = True)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    #threading.Thread(None, reactor.run, None).start()
    print "Starting websocket server"
    reactor.run()

    whiteboard.shutdown()
コード例 #4
0
    def __init__(self, port, debug):
        if debug:
            log.startLogging(sys.stdout)

        self.server = WampServerFactory("ws://localhost:"+ str(port), debug)
        self.server.protocol = LogeeProtocol
        listenWS(self.server)
コード例 #5
0
ファイル: raspi_server.py プロジェクト: chunghay/colorful
def main():
  # Add fancy time logging.
  log.startLogging(sys.stdout)
  
  # Get arguments, some of which can be set as flag options.
  args = getArguments()
  
  # Create connection to serial port.
#  serial_input = serial.Serial(args.serial_port_name, args.baud_rate)
  i2c_input = openI2CBus()

  # Create factory.
  factory = BroadcastServerFactory("ws://%s:%d" % (args.address,
                                   args.port_number),
                                   debug = False)
  factory.protocol = BroadcastServerProtocol
  websocket.listenWS(factory)
  
  # Create one more thread. There's a main thread already.
#  thread = threading.Thread(target=readSerialData, args=(serial_input, factory))
  thread = threading.Thread(target=readI2CData, args=(i2c_input, factory))
  thread.daemon = True
  thread.start()
  
  # Start handling requests across websocket.
  reactor.run()
コード例 #6
0
ファイル: server.py プロジェクト: explodes/sock-share
def main(host, port):
    url = "ws://%s:%s" % (host, port)
    print 'Serving at: %s' % url
    factory = websocket.WebSocketServerFactory(url)
    factory.protocol = WebShareServerProtocol
    websocket.listenWS(factory)
    reactor.run()
コード例 #7
0
ファイル: sockServer.py プロジェクト: dpmack/Project1536
def main(curDir):
    class WhiteboardServerProtocol(WebSocketServerProtocol):
        def onConnect(self, connectionRequest):
            whiteboard.addClient(self)
            return None

        def onMessage(self, msg, binary):
            whiteboard.processMessage(self, msg)

    os.chdir(curDir)
    
    #log.startLogging(sys.stdout)
    debugWS = False
    debugWhiteboard = False
    whiteboard = WhiteboardServer(debugWhiteboard)

    factory = WebSocketServerFactory("ws://localhost:9000",
                                     debug = debugWS,
                                     debugCodePaths = debugWS)

    factory.protocol = WhiteboardServerProtocol
    #factory.setProtocolOptions(allowHixie76 = True)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    #threading.Thread(None, reactor.run, None).start()
    print "Starting websocket server"
    reactor.run()

    whiteboard.shutdown()
コード例 #8
0
ファイル: app.py プロジェクト: TonicArtos/keysocket
    def __init__(self):
        # set up the glib main loop.
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
        bus_object = bus.get_object('org.gnome.SettingsDaemon',
                                    '/org/gnome/SettingsDaemon/MediaKeys')

        # this is what gives us the multi media keys.
        dbus_interface = 'org.gnome.SettingsDaemon.MediaKeys'
        bus_object.GrabMediaPlayerKeys("MediaKeySocketServer",
                                       0,
                                       dbus_interface=dbus_interface)

        # connect_to_signal registers our callback function.
        bus_object.connect_to_signal('MediaPlayerKeyPressed', self.on_mediakey)

        self.statusicon = gtk.StatusIcon()
        self.statusicon.set_from_file('icon48.png')
        self.statusicon.connect('popup-menu', self.right_click_event)
        self.statusicon.set_tooltip('KeySockets')

        self.factory = KeySocketServerFactory('ws://localhost:{}'.format(PORT),
                                              debug=True)

        listenWS(self.factory)
        reactor.run()
コード例 #9
0
def main():
    """ Main method for the websocket server """
    LOG.info('main: Start')
    udp_steward = UDPConnectionSteward()
    udp_steward.start()

    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/Dokumenter/websockets/autobahn/keys/server.key',
        '/home/kenni/Dokumenter/websockets/autobahn/keys/server.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9001", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9001
    listenWS(factory, context_factory)

    try:
        reactor.run()  # pylint: disable=E1101
        time.sleep(1)
        LOG.info('main: Keyboard interrupt, websocket reactor stopped')
        udp_steward.stop()
        time.sleep(1)
        LOG.info('main: UPD Steward stopped')
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    LOG.info('main: Ended')
    raw_input('All stopped. Press enter to exit')
コード例 #10
0
    def __init__(self, url):
        WebSocketServerFactory.__init__(self, url)
        self.clients = []
        self.tickGap = 5
        self.tickSetup()

        listenWS(self)
コード例 #11
0
ファイル: raspi_server.py プロジェクト: chunghay/colorful
def main():
    # Add fancy time logging.
    log.startLogging(sys.stdout)

    # Get arguments, some of which can be set as flag options.
    args = getArguments()

    # Create connection to serial port.
    #  serial_input = serial.Serial(args.serial_port_name, args.baud_rate)
    i2c_input = openI2CBus()

    # Create factory.
    factory = BroadcastServerFactory("ws://%s:%d" %
                                     (args.address, args.port_number),
                                     debug=False)
    factory.protocol = BroadcastServerProtocol
    websocket.listenWS(factory)

    # Create one more thread. There's a main thread already.
    #  thread = threading.Thread(target=readSerialData, args=(serial_input, factory))
    thread = threading.Thread(target=readI2CData, args=(i2c_input, factory))
    thread.daemon = True
    thread.start()

    # Start handling requests across websocket.
    reactor.run()
コード例 #12
0
ファイル: abserver.py プロジェクト: creilly/sitzlabexpcontrol
def runServer(
        WAMP,
        URL,
        Protocol = BaseServerProtocol,
        Factory = BaseServerFactory,
        debug = False,
        outputToConsole = False,
        args = [],
        kwargs = {}
):
    """
    start up a WAMP server

    @type WAMP: BaseWAMP

    @param URL: IP addres to host from
    @type URL: string

    @param debug: if True, prints all messages,
        including WAMP transmissions, to console.
        if False WAMP transmission aren't logged    
    @type debug: boolean
    """
    import sys
    import os
    os.system('title %s' % WAMP.__wampname__)
    Factory.protocol = Protocol
    factory = Factory(URL, debugWamp = debug)
    wamp = factory.wamp = WAMP(factory,*args,**kwargs)
    yield wamp.onReady
    log.startLogging(
        sys.stdout if outputToConsole or debug else open('serverlogs/' + WAMP.__name__ + '.log','a')
    )
    listenWS(factory)
コード例 #13
0
ファイル: websocket.py プロジェクト: gilligan/bebop
def run_websocket(host='127.0.0.1', port=1983):
    '''
    Run websocket server.
    '''
    websocket_server = BebopWebSocketServer("ws://%s:%s" % (host, port))
    listenWS(websocket_server)
    return websocket_server
コード例 #14
0
def main():
    parser = get_argparser()
    args = parser.parse_args()

    geoip_db_path = args.geoip_db
    if not geoip_db_path:
        print "geoip_db not set, defaulting to %r" % DEFAULT_GEOIP_DB
        geoip_db_path = DEFAULT_GEOIP_DB
    open(geoip_db_path).close()  # basic readability check
    try:
        bcast_log.setLevel(getattr(logging, args.loglevel.upper()))
    except:
        print 'warning: invalid log level'
        bcast_log.setLevel(logging.WARN)
    if args.debug:
        bcast_log.setLevel(logging.DEBUG)
    ws_listen_addr = 'ws://localhost:%d' % (args.port, )
    ServerFactory = BroadcastServerFactory
    factory = ServerFactory(ws_listen_addr,
                            project=args.project,
                            lang=args.lang,
                            geoip_db=geoip_db_path,
                            geoip_update_interval=args.geoip_update_interval,
                            debug=DEBUG or args.debug,
                            debugCodePaths=DEBUG)
    factory.protocol = BroadcastServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    listenWS(factory)
    reactor.run()
コード例 #15
0
def main():
    log.startLogging(sys.stderr)

    conf_file = os.path.join(
        xdg.BaseDirectory.save_config_path('socialsound'),
        'config.ini')
    config = ConfigObj(conf_file)

    username = config['Pandora']['username']
    password = config['Pandora']['password']

    proxy = config.get('Proxy', {})
    proxy_host = proxy.get('host', None)
    proxy_port = proxy.get('port', None)
    proxy = {}
    if proxy_host: proxy['proxy_host'] = proxy_host
    if proxy_port: proxy['proxy_port'] = proxy_port

    # Start websocket listener
    factory = PandoraFactory("ws://localhost:9000", debug=False,
                             username=username, password=password, **proxy)
    factory.protocol = PandoraProtocol
    listenWS(factory)

    # Start the MPD client factory.
    factory.player = PlayerFactory()
    reactor.connectTCP(MPD_HOST, MPD_PORT, factory.player)

    reactor.run()
コード例 #16
0
ファイル: monitor_websocket.py プロジェクト: hatnote/wikimon
def main():
    parser = get_argparser()
    args = parser.parse_args()

    geoip_db_path = args.geoip_db
    if not geoip_db_path:
        print "geoip_db not set, defaulting to %r" % DEFAULT_GEOIP_DB
        geoip_db_path = DEFAULT_GEOIP_DB
    open(geoip_db_path).close()  # basic readability check
    try:
        bcast_log.setLevel(getattr(logging, args.loglevel.upper()))
    except:
        print 'warning: invalid log level'
        bcast_log.setLevel(logging.WARN)
    if args.debug:
        bcast_log.setLevel(logging.DEBUG)
    ws_listen_addr = 'ws://localhost:%d' % (args.port,)
    ServerFactory = BroadcastServerFactory
    factory = ServerFactory(ws_listen_addr,
                            project=args.project,
                            lang=args.lang,
                            geoip_db=geoip_db_path,
                            geoip_update_interval=args.geoip_update_interval,
                            debug=DEBUG or args.debug,
                            debugCodePaths=DEBUG)
    factory.protocol = BroadcastServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    listenWS(factory)
    reactor.run()
コード例 #17
0
    def __init__(self, url):
        WebSocketServerFactory.__init__(self, url)
        self.clients = []
        self.tickGap = 5
        self.tickSetup()

        listenWS(self)
コード例 #18
0
def test_server(wsuri, wsuri2=None):

    dealer = Dealer()

    if wsuri2 is None:
        calculator = Calculator()
        dealer.register("http://myapp.com/", calculator)

    broker = Broker()

    class MyPubSubServerProtocol(WampServerProtocol):
        def onSessionOpen(self):
            self.setBroker(broker)
            self.setDealer(dealer)

    wampFactory = WampServerFactory(wsuri)
    wampFactory.protocol = MyPubSubServerProtocol
    listenWS(wampFactory)

    if wsuri2:

        class MyPubSubClientProtocol(WampClientProtocol):
            def onSessionOpen(self):
                self.setBroker(broker)
                self.setDealer(dealer)

        factory = WampClientFactory(wsuri2)
        factory.protocol = MyPubSubClientProtocol
        connectWS(factory)
コード例 #19
0
 def initializeWebSocket(self):##Starts the WebSocket
     log.startLogging(sys.stdout)##Create a logfile (not necessary)
     self.factory = WebSocketServerFactory(hostip, debug = False)
     self.factory.protocol = EchoServerProtocol ##assign our Protocol to send/receive Messages
     listenWS(self.factory)
     
     reactor.run(installSignalHandlers=0)##"installSignalHandlers=0" Necessary for Multithreading
コード例 #20
0
ファイル: server.py プロジェクト: zlalanne/msp430-webcontrol
def main():

    server_url = "ws://%s:%d" % (SERVER, WS_PORT)

    if DEBUG:
        log.startLogging(sys.stdout)

    # WebSocket Factory for communicating with browser
    ws_factory = MSP430SocketServerFactory(server_url, debug=DEBUG,
                                           debugCodePaths=DEBUG)
    ws_factory.protocol = MSP430ServerProtocol

    # TCP Server for communicating with MSP430 and Django Application
    web_factory = protocol.Factory()
    web_factory.protocol = WebServerProtocol

    if DEBUG:
        web_factory.protocol.debug = True

    # Need to know how to communicate both directions
    web_factory.ws_factory = ws_factory
    ws_factory.web_factory = web_factory

    listenWS(ws_factory)
    reactor.listenTCP(HTTP_PORT, web_factory)

    reactor.run()
コード例 #21
0
ファイル: WebDisplay.py プロジェクト: AndyWoodly/blinken
    def __init__(self):
        log.startLogging(sys.stdout)

        self.factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
        self.factory.protocol = WebDisplay
        listenWS(self.factory)

        reactor.run()
コード例 #22
0
ファイル: web.py プロジェクト: benrady/roost
 def startService(self):
   service.Service.startService(self)
   root = static.File(self.web_dir) 
   root.putChild('services', ServiceResource())
   self.server = internet.TCPServer(self.port, server.Site(root)).setServiceParent(self.parent)
   factory = websocket.WebSocketServerFactory("ws://localhost:9090")
   factory.protocol = EventsWebsocket
   websocket.listenWS(factory)
コード例 #23
0
def startServer(wsuri, sslKey = None, sslCert = None, debug = False):
   factory = TesteeServerFactory(wsuri, debug)
   if sslKey and sslCert:
      sslContext = ssl.DefaultOpenSSLContextFactory(sslKey, sslCert)
   else:
      sslContext = None
   listenWS(factory, sslContext)
   return True
コード例 #24
0
def startServer(wsuri, sslKey=None, sslCert=None, debug=False):
    factory = TesteeServerFactory(wsuri, debug)
    if sslKey and sslCert:
        sslContext = ssl.DefaultOpenSSLContextFactory(sslKey, sslCert)
    else:
        sslContext = None
    listenWS(factory, sslContext)
    return True
コード例 #25
0
def main():

   log.startLogging(sys.stdout)

   factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
   factory.protocol = EchoServerProtocol
   listenWS(factory)

   reactor.run()
コード例 #26
0
ファイル: WebDisplay.py プロジェクト: AndyWoodly/blinken
    def __init__(self):
        log.startLogging(sys.stdout)

        self.factory = WebSocketServerFactory("ws://localhost:9000",
                                              debug=False)
        self.factory.protocol = WebDisplay
        listenWS(self.factory)

        reactor.run()
コード例 #27
0
ファイル: ws.py プロジェクト: jakebarnwell/PythonGenerator
	def run ( self ):
			log.startLogging(sys.stdout)

			factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
			factory.protocol = PushServerProtocol
			listenWS(factory)
			
			reactor.run()
			
			
			
コード例 #28
0
def start_webserver(options, protocol=wamp.ServerProtocol, disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.host : the interface for the web-server to listen on
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    # setup the server-factory
    wampFactory = wamp.ReapingWampServerFactory(
        "ws://%s:%d" % (options.host, options.port), options.debug, options.timeout
    )
    wampFactory.protocol = protocol

    # Do we serve static content or just websocket ?
    if len(options.content) == 0:
        # Only WebSocket
        listenWS(wampFactory)
    else:
        # Static HTTP + WebSocket
        wsResource = WebSocketResource(wampFactory)

        root = File(options.content)
        root.putChild("ws", wsResource)

        site = Site(root)

        reactor.listenTCP(options.port, site)

    # Work around to force the output buffer to be flushed
    # This allow the process launcher to parse the output and
    # wait for "Start factory" to know that the WebServer
    # is running.
    for i in range(200):
        log.msg("+" * 80, logLevel=logging.CRITICAL)

    # Start factory and reactor
    wampFactory.startFactory()
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()
    wampFactory.stopFactory()
コード例 #29
0
def startServer(wsuri, sslKey = None, sslCert = None, debug = False):
   factory = BroadcastServerFactory(wsuri, debug)
   if sslKey and sslCert:
      sslContext = ssl.DefaultOpenSSLContextFactory(sslKey, sslCert)
   else:
      sslContext = None
   listenWS(factory, sslContext)

   webdir = File(pkg_resources.resource_filename("autobahntestsuite", "web/broadcastserver"))
   web = Site(webdir)
   reactor.listenTCP(8080, web)

   return True
コード例 #30
0
ファイル: wsserver.py プロジェクト: caedesvvv/ghost
def start_socket(cb):
   log.startLogging(sys.stdout)

   #contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
   #                                                  'keys/server.crt')

   factory = LocalServerFactory("ws://localhost:9000", cb)
   #factory = LocalServerFactory("wss://localhost:9000",
   #                            debug = 'debug' in sys.argv)

   listenWS(factory)
   #listenWS(factory, contextFactory)

   return factory
コード例 #31
0
ファイル: vwc.py プロジェクト: msergdeez/vwc-tx
    def __init__(self, port_ws=6455, port_http=8000):
        static_dir = path.join(path.dirname(__file__), 'web-static')
        resource = File(static_dir)
        self.web_factory = Site(resource)
        self.ws_factory = WampServerFactory("ws://0.0.0.0:%d" % port_ws)
        self.ws_factory.protocol = RpcServerProtocol
        self.ws_factory.protocol.owner = self

        self.gui = GtkGUI()
        self.gui.set_layout('v01')

        listenWS(self.ws_factory)
        reactor.listenTCP(port_http, self.web_factory)
        reactor.run()
コード例 #32
0
ファイル: server.py プロジェクト: jomido/tswss
def setup_websocket_component(port=6789):

    """

    Setup and start the websocket portion of the server.

    """

    log.startLogging(sys.stdout)

    address = "ws://localhost:" + str(port)
    server = MyWebSocketServer(address)

    listenWS(server)
コード例 #33
0
ファイル: sookie.py プロジェクト: Dvergar/sookie
def start_server(port, appmanager, protocol, apprate, netrate):
    port = 9999
    manager = Manager(appmanager, apprate, netrate)  # TODO remove manager = ?

    DefaultConnection.__bases__ += (Protocol, protocol, Sender)  # WTF inheritance
    echofactory = Factory()
    echofactory.protocol = DefaultConnection
    reactor.listenTCP(port, echofactory)
    # WEBSOOOOOCKKEEEET
    WSConnection.__bases__ += (WebSocketServerProtocol, protocol, Sender)
    factory = WebSocketServerFactory("ws://localhost:" + str(port + 1))
    factory.protocol = WSConnection
    listenWS(factory)
    print "Server initialized"
    reactor.run()
コード例 #34
0
def startServer(wsuri, sslKey=None, sslCert=None, debug=False):
    factory = BroadcastServerFactory(wsuri, debug)
    if sslKey and sslCert:
        sslContext = ssl.DefaultOpenSSLContextFactory(sslKey, sslCert)
    else:
        sslContext = None
    listenWS(factory, sslContext)

    webdir = File(
        pkg_resources.resource_filename("autobahntestsuite",
                                        "web/broadcastserver"))
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    return True
コード例 #35
0
def main():

	showDialog("Permissions Fixer Started.\n\nReturn to the codebender walkthrough\nto complete the process.\n")

	try:
		ServerFactory = BroadcastServerFactory

		factory = ServerFactory("ws://*****:*****@codebender.cc\n')
コード例 #36
0
ファイル: web.py プロジェクト: thomasflyvholm/ParaView
def start_webserver(options,
                    protocol=paraviewweb_wamp.ServerProtocol,
                    disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    # setup the server-factory
    wampFactory = paraviewweb_wamp.ReapingWampServerFactory(
        "ws://localhost:%d" % options.port, options.debug, options.timeout)
    wampFactory.protocol = protocol

    # Do we serve static content or just websocket ?
    if len(options.content) == 0:
        # Only WebSocket
        listenWS(wampFactory)
    else:
        # Static HTTP + WebSocket
        wsResource = WebSocketResource(wampFactory)

        root = File(options.content)
        root.putChild("ws", wsResource)

        webgl = WebGLResource()
        root.putChild("WebGL", webgl)

        site = Site(root)

        reactor.listenTCP(options.port, site)

    # Start factory and reactor
    wampFactory.startFactory()
    if options.nosignalhandlers:
        reactor.run(installSignalHandlers=0)
    else:
        reactor.run()
    wampFactory.stopFactory()
コード例 #37
0
 def _setUpListener(self, serviceName, port, protocol, handler=None):
     url = "ws://localhost:%d"%(port)       
     factory = WebSocketServerFactory(url, debug=True, debugCodePaths=True)    
     factory.protocol = protocol
     factory.setProtocolOptions(allowHixie76=True)
     
     #HACK: add an array for observing messages
     factory.observers = [] #called for every message; for the ui to listen
     
     if handler !=None:
         factory.observers.append(handler)
     
     factory.connections = [] #all connections that are active; for the protocol to send data
     self.frontEndListeners[serviceName] = factory
     listenWS(self.frontEndListeners[serviceName]) 
     
コード例 #38
0
    def startService(self):
        log.msg("Starting %s service ..." % self.SERVICENAME)

        if self.services["config"]["admin-websocket-tls"]:
            contextFactory = TlsContextFactory(
                self.services["config"]["admin-websocket-tlskey-pem"],
                self.services["config"]["admin-websocket-tlscert-pem"],
                dhParamFilename=self.services['master'].dhParamFilename)

            uri = "wss://localhost:%d" % self.services["config"][
                "admin-websocket-port"]
        else:
            contextFactory = None

            uri = "ws://localhost:%d" % self.services["config"][
                "admin-websocket-port"]

        self.factory = AdminWebSocketFactory(uri, self.dbpool, self.services)
        self.listener = listenWS(
            self.factory,
            contextFactory,
            backlog=self.services["config"]["ws-accept-queue-size"])

        if self.services.has_key("logger"):
            self.services["logger"].setDispatch(self.dispatchAdminEvent)
        self.isRunning = True
コード例 #39
0
ファイル: server.py プロジェクト: DamnedFacts/Vernacular
def runServer():
    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    factory = WampServerFactory("ws://localhost:9000", debug=False, debugCodePaths=False, debugWamp=debug, debugApp=False)
    factory.protocol = AppServerProtocol
    factory.setProtocolOptions(allowHixie76 = True)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)
    reactor.run(installSignalHandlers=0)
コード例 #40
0
def main():
    """ Main method for the websocket server """
    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate

    # Start UDP server thread
    udp_server = ReceiveDataUDPServer()
    udp_server.start()

    # Start load monitor thread
    load_monitor = LoadMonitor()
    load_monitor.start()

    # Start the data sender thread
    data_sender = DataSender()
    data_sender.start()

    ####### SSL IMPLEMENTATION
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/certs/fysik.dtu.dk.key',
        '/home/kenni/certs/fysik.dtu.dk-NEW.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9002", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9002
    listenWS(factory, context_factory)
    ######## SSL IMPLEMENTATION END

    try:
        LOG.info('run reactor')
        reactor.run()  # pylint: disable=E1101
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    # Stop all three threads
    udp_server.stop()
    load_monitor.stop()
    data_sender.stop()

    LOG.info('main: Ended')
    #raw_input('All stopped. Press enter to exit')
    print('All stopped. Press enter to exit')
コード例 #41
0
ファイル: runner.py プロジェクト: 0dayZh/SocketRocket
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', default='ws://localhost:9001', help='Listen URL [default: %(default)s]')
    parser.add_argument('-O', '--options', default=jsondict({'failByDrop':False}), type=jsondict, action='append', help='extra options (overwrites existing) [default: %(default)s]')

    parser.add_argument('-p', '--webport', default=9090, type=int)
    parser.add_argument('-i', '--listen-interface', default='localhost', help='interface to listen on')
    parser.add_argument('-w', '--webdir', default='.')
    parser.add_argument('-d', '--debug', default=False, action='store_true', help='Debug Mode [default: %(default)s]')

    parser.add_argument('-o', '--outdir', default='./pages/results', metavar='DIR', help='Output Directory [default: %(default)s]')

    parser.add_argument('-c', '--cases', default=['*'], nargs='+', help='test cases [default: %(default)s]')
    parser.add_argument('-x', '--exclude-cases', default=[], nargs='+', help='test cases to exclude [default: %(default)s]')

    parser.add_argument('-l', '--logfile', type=argparse.FileType('w'), default=sys.stdout, help='logging file [default: stdout]')

    parser.add_argument('-t', '--exit-timeout', metavar='SECONDS', default=None, type=float, help='Will automatically exit after %(metavar)s seconds [default: %(default)s]')

    args = parser.parse_args()

    spec = args.__dict__

    log.startLogging(args.logfile)
 
    ## fuzzing server
    fuzzer = FuzzingServerFactory(spec)
    listenWS(fuzzer, interface=args.listen_interface)
 
    ## web server
    webdir = File(args.webdir)
    web = Site(webdir)
    reactor.listenTCP(args.webport, web, interface=args.listen_interface)
 
    log.msg("Using Twisted reactor class %s" % str(reactor.__class__))

    if args.exit_timeout:
        def exit_callback():
            log.msg("Exiting due to timeout (--exit-timeout/-t)")
            reactor.fireSystemEvent('shutdown')
            #reactor.stop()
            sys.exit(12)

        reactor.callLater(args.exit_timeout, exit_callback)
    
    reactor.run()
コード例 #42
0
ファイル: web.py プロジェクト: HerculesCE/ParaView
def start_webserver(options, protocol=paraviewweb_wamp.ServerProtocol, disableLogging=False):
    """
    Starts the web-server with the given protocol. Options must be an object
    with the following members:
        options.port : port number for the web-server to listen on
        options.timeout : timeout for reaping process on idle in seconds
        options.content : root for web-pages to serve.
    """
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.web.static import File
    import sys

    if not disableLogging:
        log.startLogging(sys.stdout)

    # setup the server-factory
    wampFactory = paraviewweb_wamp.ReapingWampServerFactory(
        "ws://localhost:%d" % options.port, options.debug, options.timeout)
    wampFactory.protocol = protocol

    # Do we serve static content or just websocket ?
    if len(options.content) == 0:
        # Only WebSocket
        listenWS(wampFactory)
    else:
        # Static HTTP + WebSocket
        wsResource = WebSocketResource(wampFactory)

        root = File(options.content)
        root.putChild("ws", wsResource)

        webgl = WebGLResource()
        root.putChild("WebGL", webgl);

        site = Site(root)

        reactor.listenTCP(options.port, site)

    # Start factory and reactor
    wampFactory.startFactory()
    if options.nosignalhandlers:
       reactor.run(installSignalHandlers=0)
    else:
       reactor.run()
    wampFactory.stopFactory()
コード例 #43
0
ファイル: hub_server.py プロジェクト: chunghay/colorful
def main():
  # Add fancy time logging.
  log.startLogging(sys.stdout)

  # Instantiate voting model.
  # TODO: Make separate Python script for handling the voting.
  #       Then import that script into this script.
  model = []

  # Listen to all addresses on port 9000.
  factory = BroadcastServerFactory("ws://[::]:9000", voteModel = model,
                                    debug = False)
  factory.protocol = BroadcastServerProtocol
  websocket.listenWS(factory)

  # Start handling requests across websocket.
  reactor.run()
コード例 #44
0
    def run(self, start_reactor=True):
        # Look for event classes in the source tree
        self.autodiscover()
        # Create factory
        self.factory = GatewayWampServerFactory(self.url,
                                                debugWamp=self.debug,
                                                gateway=self
                                                )
        self.factory.protocol = TelegraphyConnection
        self.factory.setProtocolOptions(allowHixie76=True)
        listenWS(self.factory)

        r = WebAppXMLRPCInterface(gateway=self)

        reactor.listenTCP(self.xmlrpc_port, server.Site(r))

        if start_reactor:
            reactor.run()
コード例 #45
0
def main():
	try:
		#initializing serial flashing etc utilities socket
		ServerFactory = BroadcastServerFactory

		factory = ServerFactory("ws://localhost:9000")
		# factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
		factory.protocol = EchoServerProtocol
		listenWS(factory)

		factory2 = WebSocketServerFactory("ws://localhost:9001")
		factory2.protocol = WebSerialProtocol
		listenWS(factory2)

		reactor.run()
	except error.CannotListenError, e:
		print "Port is already used. Exiting..."
		os._exit(0)
コード例 #46
0
ファイル: hub_server.py プロジェクト: chunghay/colorful
def main():
    # Add fancy time logging.
    log.startLogging(sys.stdout)

    # Instantiate voting model.
    # TODO: Make separate Python script for handling the voting.
    #       Then import that script into this script.
    model = []

    # Listen to all addresses on port 9000.
    factory = BroadcastServerFactory("ws://[::]:9000",
                                     voteModel=model,
                                     debug=False)
    factory.protocol = BroadcastServerProtocol
    websocket.listenWS(factory)

    # Start handling requests across websocket.
    reactor.run()
コード例 #47
0
def main():
    parser = get_argparser()
    args = parser.parse_args()
    try:
        bcast_log.setLevel(getattr(logging, args.loglevel.upper()))
    except:
        print 'warning: invalid log level'
        bcast_log.setLevel(logging.WARN)
    ws_listen_addr = 'ws://localhost:%d' % (args.port, )
    ServerFactory = BroadcastServerFactory
    factory = ServerFactory(ws_listen_addr,
                            project=args.project,
                            lang=args.lang,
                            debug=DEBUG,
                            debugCodePaths=DEBUG)
    factory.protocol = BroadcastServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    listenWS(factory)
    reactor.run()
コード例 #48
0
def main():
    """ Main method for the websocket server """
    LOG.info('main: Start')
    global LIVESOCKET  # pylint: disable=global-statement
    names = ['wss_hosts_defined', 'wss_hosts', 'wss_clients']
    LIVESOCKET = LiveSocket('websocketserver', names, sane_interval=1.0)
    LIVESOCKET.start()

    udp_steward = UDPConnectionSteward()
    udp_steward.start()

    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/certs/fysik.dtu.dk.key',
        '/home/kenni/certs/fysik.dtu.dk-NEW.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9001", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9001
    listenWS(factory, context_factory)

    try:
        reactor.run()  # pylint: disable=E1101
        time.sleep(1)
        LOG.info('main: Keyboard interrupt, websocket reactor stopped')
        udp_steward.stop()
        time.sleep(1)
        LOG.info('main: UPD Steward stopped')
        LIVESOCKET.stop()
        time.sleep(1)
        LOG.info('main: Own livesocket stoppped')
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    LOG.info('main: Ended')
    raw_input('All stopped. Press enter to exit')
コード例 #49
0
ファイル: server.py プロジェクト: hiyeshin/yoga_socket
def main():
    if WS_USE_SSL or HTTP_USE_SSL:
        contextFactory = ssl.DefaultOpenSSLContextFactory(
            'certs/server.key', 'certs/server.crt')

    if WS_USE_SSL:
        uri_type = "wss"

    else:
        uri_type = "ws"

    server_url = "%s://%s:%d" % (uri_type, SERVER, WS_PORT)

    if DEBUG:
        log.startLogging(sys.stdout)

    factory = RPISocketServerFactory(server_url,
                                     debug=DEBUG,
                                     debugCodePaths=DEBUG)
    factory.protocol = RPIServerProtocol

    sitecomm = SiteComm(factory)
    factory.sitecomm = sitecomm
    site = server.Site(sitecomm)

    if WS_USE_SSL:
        listenWS(factory, contextFactory)

    else:
        listenWS(factory)

    if HTTP_USE_SSL:
        reactor.listenSSL(HTTP_PORT, site, contextFactory)
    else:
        reactor.listenTCP(HTTP_PORT, site)

    if PROVIDEFLASHSOCKETPOLICYFILE:
        socketfactory = twistedsockets.Factory()
        socketfactory.protocol = FlashSocketPolicyServerProtocol
        reactor.listenTCP(843, socketfactory)

    reactor.run()
コード例 #50
0
def main(argv):

    try:
        opts, args = getopt.getopt(argv, 'h', ['help'])

    except getopt.GetoptError:
        usage()

    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()

    print 'The count server is gonna start ...'

    factory = WebSocketServerFactory('ws://localhost:9000')
    factory.protocol = CountServerProtocol
    listenWS(factory)

    reactor.callWhenRunning(countForEver)
    reactor.run()
コード例 #51
0
def run_autobahn_server(host="127.0.0.1", port=9003):
    from autobahntestsuite import choosereactor
    import autobahn
    from autobahn.websocket import listenWS
    from twisted.internet import reactor
    from autobahn.websocket import WebSocketServerFactory, \
         WebSocketServerProtocol

    class ServerProtocol(WebSocketServerProtocol):
        def onMessage(self, msg, binary):
            self.sendMessage(msg, binary)

    class ServerFactory(WebSocketServerFactory):
        protocol = ServerProtocol

    factory = ServerFactory("ws://%s:%d" % (host, port))
    factory.setProtocolOptions(failByDrop=False)
    logger.warning("Serving Autobahn server on %s:%s" % (host, port))
    listenWS(factory, None)
    reactor.run()
コード例 #52
0
def main(reactor, cred, masterIP, masterPort, consolePort, extIP, extPort,
         commPort, pkgPath, customConverters):
    log.startLogging(sys.stdout)

    def _err(reason):
        print(reason)
        reactor.stop()

    factory = PBClientFactory()
    reactor.connectTCP(masterIP, masterPort, factory)

    rosPath = []
    for path in get_ros_paths() + [p for p, _ in pkgPath]:
        if path not in rosPath:
            rosPath.append(path)

    loader = Loader(rosPath)
    converter = Converter(loader)

    for customConverter in customConverters:
        # Get correct path/name of the converter
        module, className = customConverter.rsplit('.', 1)

        # Load the converter
        mod = __import__(module, fromlist=[className])
        converter.addCustomConverter(getattr(mod, className))

    client = RobotClient(reactor, masterIP, consolePort, commPort, extIP,
                         extPort, loader, converter)
    d = factory.login(cred, client)
    d.addCallback(lambda ref: setattr(client, '_avatar', ref))
    d.addErrback(_err)

    # portal = Portal(client, (client,))
    robot = CloudEngineWebSocketFactory(client,
                                        'ws://localhost:{0}'.format(extPort))
    listenWS(robot)

    reactor.addSystemEventTrigger('before', 'shutdown', client.terminate)
    reactor.run()
コード例 #53
0
def run_server ():
	reactor.listenTCP(8789, pb.PBServerFactory(ExperimentMarshal()))
	log.msg("PB listening on port 8789")

	factory = WampServerFactory("ws://localhost:9000")
	factory.protocol = LabspiralServerProtocol
	listenWS(factory)
	log.msg("WS listening on port 9000")

	ExperimentMarshal.publish = factory.dispatch

	root = resource.Resource()
	root.putChild("", Root())
	root.putChild("experiments", ExperimentList())
	root.putChild("resources", static.File("resources"))
	site = server.Site(root)
	reactor.listenTCP(8001, site)
	log.msg("HTTP listening on port 8001")

	reactor.run()

	log.msg("Server stopped")
コード例 #54
0
def runwamp(logfile=None, debug=True):
    if logfile is None:
        log.startLogging(sys.stdout)
    '''
    factory = WampServerFactory("ws://%s:9000" % socket.gethostname(),
                                debugWamp=debug)
    '''

    factory = ""
    host_name = socket.gethostname()
    if host_name == 'ip-172-31-29-49':
        factory = WampServerFactory("ws://oposod.com:9000", debugWamp=None)
    else:
        factory = WampServerFactory("ws://localhost:9000", debugWamp=debug)
    factory.protocol = PubSubServer1
    factory.setProtocolOptions(allowHixie76=True)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(9090, web)

    reactor.run()
コード例 #55
0
def main():
    # Explicitly set dbus main loop.
    DBusGMainLoop(set_as_default=True)

    # Wake up the settings manager dbus service.
    try:
        settings_bus = SessionBus().get_object('org.gnome.SettingsDaemon',
                                               '/org/gnome/SettingsDaemon')
    except DBusException as e:
        dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT,
                                   gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                                   GSM_NOT_FOUND_MESSAGE)
        dialog.run()
        dialog.destroy()
        return
    try:
        settings_bus.Awake(dbus_interface='org.gnome.SettingsDaemon')
    except DBusException as e:
        # May not always be wakeable. That's Ok.
        pass

    # Create server.
    factory = BroadcastServerFactory('ws://localhost:1337')
    listenWS(factory)

    # Start twisted.
    reactor.startRunning()

    # Create the tray icon. Must keep reference to prevent GC.
    icon = createTrayIcon()

    #Run GTK loop.
    gtk.main()

    # Kill twisted if it's still alive.
    if reactor.running:
        reactor.stop()
コード例 #56
0
def startServer(self, debug = False):
   ## WAMP Server for wsperf slaves
   ##
   wsperf = WsPerfMasterFactory("ws://localhost:9090")
   wsperf.debugWsPerf = debug
   listenWS(wsperf)

   ## Web Server for UI static files
   ##
   webdir = File(pkg_resources.resource_filename("autobahntestsuite", "web/wsperfmaster"))
   web = Site(webdir)
   reactor.listenTCP(8080, web)

   ## WAMP Server for UI
   ##
   wsperfUi = WsPerfMasterUiFactory("ws://localhost:9091")
   wsperfUi.debug = debug
   wsperfUi.debugWamp = debug
   listenWS(wsperfUi)

   ## Connect servers
   ##
   wsperf.uiFactory = wsperfUi
   wsperfUi.slaveFactory = wsperf
コード例 #57
0
ファイル: echowebsocket.py プロジェクト: ktosiu/scratchbox
    def startService(self):
        log.msg("Starting %s service ..." % self.SERVICENAME)
        if self.services["config"]["echo-websocket-tls"]:
            contextFactory = TlsContextFactory(
                self.services["config"]["echo-websocket-tlskey-pem"],
                self.services["config"]["echo-websocket-tlscert-pem"],
                dhParamFilename=self.services['master'].dhParamFilename)

            uri = "wss://localhost:%d" % self.services["config"][
                "echo-websocket-port"]
        else:
            contextFactory = None

            uri = "ws://localhost:%d" % self.services["config"][
                "echo-websocket-port"]

        self.factory = EchoWebSocketFactory(uri, self.dbpool, self.services,
                                            self.reactor)
        self.listener = listenWS(
            self.factory,
            contextFactory,
            backlog=self.services["config"]["ws-accept-queue-size"])
        self.isRunning = True
コード例 #58
0
        self.tick()

    def tick(self):
        self.tickcount += 1
        self.broadcast("tick %d" % self.tickcount)
        reactor.callLater(1, self.tick)

    def register(self, client):
        if not client in self.clients:
            print "registered client " + client.peerstr
            self.clients.append(client)

    def unregister(self, client):
        if client in self.clients:
            print "unregistered client " + client.peerstr
            self.clients.remove(client)

    def broadcast(self, msg):
        print "broadcasting message '%s' .." % msg
        for c in self.clients:
            print "send to " + c.peerstr
            c.sendMessage(msg)


if __name__ == '__main__':

    log.startLogging(sys.stdout)
    factory = BroadcastServerFactory("ws://localhost:9000")
    listenWS(factory)
    reactor.run()