def run(self):
     root = File('.')
     site = WebSocketSite(root)
     site.addHandler('/test', TickerHandler)
     print "\nWebSocket Server starts at %d" % self.port
     reactor.listenTCP(self.port, site)
     reactor.run(installSignalHandlers=0)
def main(root_path=None, port=9091, proxy_url="/proxy", 
         proxy_host="www.google.com", proxy_port=80):
    ################
    # setup log
    log.startLogging(sys.stdout)
    ################
    # setup webserver
    webserver = None
    if root_path:
        # serve static files
        if not root_path.startswith("/"):
            root_path = os.path.join(os.path.dirname(__file__), root_path)
        root = static.File(root_path)
        webserver = WebSocketSite(root)
    else:
        # serve no files, only websockets
        webserver = WebSocketSite(resource.NoResource())

    ################
    # setup tcp proxy for a service
    # When web browser connects on WebSocket it will redirect to 
    # proxy_host/proxy_port
    proxy = ProxyFactory(proxy_host, proxy_port)
    ws = WebSocketWrapperFactory(proxy)

    webserver.addHandler(proxy_url, ws.buildHandler)

    ################
    # Run webserver
    reactor.listenTCP(port, webserver)
    reactor.run()
Example #3
0
def main(root_path=".", port=9091):
    ################
    # setup log
    log.startLogging(sys.stdout)
    ################
    # setup webserver
    webserver = None
    if root_path:
        # serve static files
        if not root_path.startswith("/"):
            root_path = os.path.join(os.path.dirname(__file__), root_path)
        root = static.File(root_path)
        webserver = WebSocketSite(root)
    else:
        # serve no files, only websockets
        webserver = WebSocketSite(resource.NoResource())

    ################
    # setup echo factory

    # add echo handler url
    webserver.addHandler("/ws/echo", Echo)

    ################
    # Run webserver
    reactor.listenTCP(port, webserver)
    reactor.run()
Example #4
0
def setup(scope, port=21000):
    MainHandler.scope = scope
    MainHandler.setup()
    global root
    root = File(".")
    root.putChild('_pyreg',File(os.path.dirname(__file__)+'/_pyreg'))
    site = WebSocketSite(root)
    site.addHandler("/ws/websocket", MainHandler)
    reactor.listenTCP(port, site)
    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/bar", self.ServerHandlerClass)
        self.p = reactor.listenTCP(0, self.site, interface="127.0.0.1")

        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(url)
        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)
class BadURL(ClientTestCase):
    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/bar", TestHandler)
        self.p = reactor.listenTCP(0, self.site, interface="127.0.0.1")

    def tearDown(self):
        self.p.stopListening()

    def got_response(self, response):
        self.assertIsInstance(response, HandshakeResponseError)
        self.assertEqual(response.args[0], "HTTP/1.1 404 Not Found")

    def test_BadURL(self):
        url = "ws://localhost:%d/bogus" % self.p.getHost().port
        self.factory = TestClientFactory(url)
        self.factory.handshakeErrorDeferred.addCallback(self.got_response)
        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)
        return self.factory.handshakeErrorDeferred
Example #7
0
File: web.py Project: chizu/hashi
def start():
    root = Hashioki()
    root.putChild('static', File('static'))

    rest_api = API()
    root.putChild('api', rest_api)
    rest_api.putChild('session', APISession())
    rest_api.putChild('login', APILogin())
    rest_api.putChild('whoami', APIWhoAmI())
    rest_api.putChild('logout', APILogout())
    irc_network = IRCNetwork()
    rest_api.putChild('networks', irc_network)

    site = WebSocketSite(root)
    site.addHandler('/api/websocket', APISocket)
    site.sessionFactory = LongSession

    reactor.listenTCP(8080, site)

    return site
Example #8
0
 def start(self):
     try:
         root = Resource()
         root.putChild('play', PlayHandler(self._media_backend, self))
         root.putChild('scrub', ScrubHandler(self._media_backend, self))
         root.putChild('rate', RateHandler(self._media_backend, self))
         root.putChild('photo', PhotoHandler(self._media_backend, self))
         root.putChild('authorize', AuthorizeHandler(self._media_backend, self))
         root.putChild('server-info', ServerInfoHandler(self._media_backend, self))
         root.putChild('slideshow-features', SlideshowFeaturesHandler(self._media_backend, self))
         root.putChild('playback-info', PlaybackInfoHandler(self._media_backend, self))
         root.putChild('stop', StopHandler(self._media_backend, self))
         root.putChild('setProterpy', SetProterpyHandler(self._media_backend, self))
         root.putChild('getProterpy', GetProterpyHandler(self._media_backend, self))
         self.reverseHandler = ReverseHandler()
         site = WebSocketSite(root)
         site.addHandler('/reverse', self.reverseHandler)
         port = self._port
         reactor.listenTCP(port, site, interface='0.0.0.0')
     except Exception as ex:
         print('Exception(Can be ignored): ' + str(ex), __name__, 'W')
class SubProtocol(ClientTestCase):
    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/bar", TestHandlerWithSubProtocols)
        self.p = reactor.listenTCP(0, self.site, interface="127.0.0.1")

    def tearDown(self):
        self.p.stopListening()

    def roadrunner(self):
        pass

    def beepbeep(self):
        pass

    def test_AcceptSubProtocol(self):
        def got_connection(response):
            self.assertEqual(self.factory.client.subprotocol, self.beepbeep)
            self.factory.client.close()

        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(
            url, subprotocolsAvailable={"roadrunner.acme.com": self.roadrunner, "beepbeep.acme.com": self.beepbeep}
        )
        self.factory.connectionEstablishedDeferred.addCallback(got_connection)

        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)
        return self.factory.connectionLostDeferred.addErrback(self.clean_disconnection)

    def test_RefuseSubProtocol(self):
        def got_response(response):
            self.assertIsInstance(response, HandshakeResponseError)
            self.assertEqual(response.args[0], "HTTP/1.1 400 Unhandled subprotocol")

        self.trace_lost_connection = lambda _: None
        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(url, subprotocolsAvailable={"bogus.acme.com": None, "bogos.acme.com": None})
        self.factory.handshakeErrorDeferred.addCallback(got_response)
        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)
        return self.factory.handshakeErrorDeferred
 def start(self):
     try:
         root = Resource()
         root.putChild('play', PlayHandler(self._media_backend, self))
         root.putChild('scrub', ScrubHandler(self._media_backend, self))
         root.putChild('rate', RateHandler(self._media_backend, self))
         root.putChild('photo', PhotoHandler(self._media_backend, self))
         root.putChild('authorize', AuthorizeHandler(self._media_backend, self))
         root.putChild('server-info', ServerInfoHandler(self._media_backend, self))
         root.putChild('slideshow-features', SlideshowFeaturesHandler(self._media_backend, self))
         root.putChild('playback-info', PlaybackInfoHandler(self._media_backend, self))
         root.putChild('stop', StopHandler(self._media_backend, self))
         root.putChild('setProterpy', SetProterpyHandler(self._media_backend, self))
         root.putChild('getProterpy', GetProterpyHandler(self._media_backend, self))
         root.putChild('premium', PremiumHandler(self._media_backend, self))
         self.reverseHandler = ReverseHandler()
         site = WebSocketSite(root)
         site.addHandler('/reverse', self.reverseHandler)
         port = self._port
         reactor.listenTCP(port, site, interface='0.0.0.0')
     except Exception as ex:
         print ('Exception(Can be ignored): ' + str(ex), __name__, 'W')
Example #11
0
				else:
					timers[name]=reactor.callLater(int(time), self.dispatch, command)
				print timers
			else:
				self.dispatch(data)
	
	def connectionMade(self):
		print 'Connected to client..',

	def connectionLost(self, reason):
		print 'Lost connection.'
		if self.authenticated:
			WebSockClients.remove(self)

root = static.File(WEBSITE_ROOT)
site = WebSocketSite(root)
site.addHandler('/ws', WSHandler)
#reactor.listenTCP(WEBSOCKET_PORT, site) #If you choose not to use wss, update index.html appropriately.
reactor.listenSSL(WEBSOCKET_PORT, site, ssl.DefaultOpenSSLContextFactory(SSL_PRIVKEY, SSL_CERT,))
print "Web socket listening on port: ", WEBSOCKET_PORT



################################################################################
################################################################################


if __name__ == '__main__':

	# Start reactor:
	reactor.run()
		}
          self.transport.write(json.dumps(ret))
          reactor.callLater(1/self._freq,self.senddata)
    def power_on(self):
          tunel.power_on()
    def power_off(self):
          tunel.power_off()
    def fans_start(self):
          tunel.fans_controller.power_on()
    def fans_stop(self):
          tunel.fans_controller.power_off()
    def fans_speed(self,speed):
          tunel.fans_controller.set_speed(speed)
    def set_freq(self,freq):
          self._freq = freq
    def start_measuring(self):
          _saving=True
    def stop_measuring(self):
          _saving=False
    def set_servo_angle(self,angle):
          if angle>=-90 and angle <=90:
              tunel.set_angle(angle)
if __name__ == "__main__":
    root = File(".")
    site = WebSocketSite(root)
    site.addHandler("/echo", Tunelhandler)
    reactor.listenTCP(5563, site)
    reactor.run()
      

Example #13
0
      except KeyError:
        data = None
      try:
        response_id = j['response_id']
      except KeyError:
        response_id = None

      if hasattr(self, fn):
        getattr(self, fn)(data, response_id)
      else:
        self.log_error("No API for " + str(op))

    except KeyError:
      self.log_error("API error")

  @response
  def api_get_player_id(self, data, response_id):
    return ('get_player_id', self._uuid, response_id)

  def connectionLost(self, reason):
    self.log("Connection Lost: " + str(reason))

if __name__ == "__main__":
  from twisted.internet import reactor
  
  root = RootResource()
  site = WebSocketSite(root)
  site.addHandler('/game', GameHandler)
  reactor.listenTCP(9000, site)
  reactor.run()
Example #14
0
        policy = (
            '<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM '
            '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">'
            '<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>'
        )
        self.transport.write(policy)
        self.transport.loseConnection()


if __name__ == "__main__":
    from twisted.internet import reactor

    # run our websocket server
    # serve index.html from the local directory
    root = File(".")
    site = WebSocketSite(root)

    # test handler
    site.addHandler("/test", Testhandler)

    # example of wrapping a factory in order to provide WebSockets transport
    echo_factory_wrapped = WebSocketWrapperFactory(EchoFactory())
    site.addHandler("/echo", echo_factory_wrapped.buildHandler)

    reactor.listenTCP(8080, site)
    # run policy file server
    # factory = Factory()
    # factory.protocol = FlashSocketPolicy
    # reactor.listenTCP(843, factory)
    reactor.run()
Example #15
0

if __name__ == "__main__":
    root = RootResource()

    # Mount the directories containing our static files
    staticDir = static.File("./static/")
    staticDir.putChild("algorithm", static.File("../algorithm/"))
    staticDir.directoryListing = lambda: error.ForbiddenResource()
    root.putChild("static", staticDir)

    # Create a resource that spawns new sessions as they are accessed
    root.putChild("session", SessionDispatcherResource())

    # Create a transport endpoint that can be accessed using a WebSocket
    site = WebSocketSite(root)
    site.addHandler("/transport", TransportHandler)

    # Start listening
    listener = reactor.listenTCP(PORT, site)

    print "EXPERIMENTAL SERVER - Do not use in production environments!"
    print "Read the README file before using this."
    print

    listeningHost = listener.getHost()
    print "Listening for HTTP connections on %s:%s" % (listeningHost.host, listeningHost.port)
    print

    reactor.run()
class Extensions(ClientTestCase):
    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/bar", TestHandlerWithExtensions)
        self.p = reactor.listenTCP(0, self.site, interface="127.0.0.1")

    def tearDown(self):
        self.p.stopListening()

    def test_refuseExtensions(self):
        """
        Test that the connection is accepted even when the extention
        proposed by the client is not
        by the server, and that the extension is not selected.
        """

        def got_connection(response):
            self.assertEqual(self.factory.client.extensions, [])
            self.factory.client.close()

        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(url, extensionsAvailable=[RoadRunnerExtension()])
        self.factory.connectionEstablishedDeferred.addCallback(got_connection)
        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)

        return self.factory.connectionLostDeferred.addErrback(self.clean_disconnection)

    def test_acceptExtensions(self):
        """
        Test that the connection is accepted when at least one extension
        is accepted.
        Also, test that the parameters are duely selected.
        """

        def got_connection(response):
            self.assertEqual(len(self.factory.client.extensions), 1)
            self.assertIsInstance(self.factory.client.extensions[0], ZipExtension)
            self.assertEqual(self.factory.client.extensions[0].params, {"arg1": "foo", "arg2": "bar"})
            self.factory.client.close()

        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(
            url, extensionsAvailable=[RoadRunnerExtension(), ZipExtension(params={"arg1": "foo", "arg2": "bar"})]
        )
        self.factory.connectionEstablishedDeferred.addCallback(got_connection)

        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)
        return self.factory.connectionLostDeferred.addErrback(self.clean_disconnection)

    def test_processExtension(self):
        """
        Test the processing of the selected extensions
        """

        def send(_):
            self.factory.expectedResponses = 1
            self.sent_data = self.simpleData * 100
            self.factory.client.write(self.sent_data)
            self.factory.client.write("END")

        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(url, extensionsAvailable=[ZipExtension()])
        self.factory.connectionEstablishedDeferred.addCallback(send)

        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)
        return self.factory.connectionLostDeferred.addErrback(self.clean_disconnection).addCallback(self.checkResponse)

    def checkResponse(self, _):
        self.assertEqual(self.factory.frames[0], self.sent_data)
Example #17
0
 def setUp(self):
     self.site = WebSocketSite(Resource())
     self.site.addHandler("/test", TestHandler)
Example #18
0
class WebSocketSiteTestCase(TestCase):
    """
    Tests for L{WebSocketSite}.
    """

    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/test", TestHandler)


    def renderRequest(self, headers=None, url="/test", ssl=False,
                      queued=False, body=None):
        """
        Render a request against C{self.site}, writing the WebSocket
        handshake.
        """
        if headers is None:
            headers = [
                ("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                ("Host", "localhost"), ("Origin", "http://localhost/")]
        channel = DummyChannel()
        if ssl:
            channel.transport = channel.SSL()
        channel.site = self.site
        request = self.site.requestFactory(channel, queued)
        for k, v in headers:
            request.requestHeaders.addRawHeader(k, v)
        request.gotLength(0)
        request.requestReceived("GET", url, "HTTP/1.1")
        if body:
            request.channel._transferDecoder.finishCallback(body)
        return channel


    def test_multiplePostpath(self):
        """
        A resource name can consist of several path elements.
        """
        handlers = []
        def handlerFactory(request):
            handler = TestHandler(request)
            handlers.append(handler)
            return handler
        self.site.addHandler("/foo/bar", handlerFactory)
        channel = self.renderRequest(url="/foo/bar")
        self.assertEquals(len(handlers), 1)
        self.assertFalse(channel.transport.disconnected)


    def test_queryArguments(self):
        """
        A resource name may contain query arguments.
        """
        handlers = []
        def handlerFactory(request):
            handler = TestHandler(request)
            handlers.append(handler)
            return handler
        self.site.addHandler("/test?foo=bar&egg=spam", handlerFactory)
        channel = self.renderRequest(url="/test?foo=bar&egg=spam")
        self.assertEquals(len(handlers), 1)
        self.assertFalse(channel.transport.disconnected)


    def test_noOriginHeader(self):
        """
        If no I{Origin} header is present, the connection is closed.
        """
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                     ("Host", "localhost")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_multipleOriginHeaders(self):
        """
        If more than one I{Origin} header is present, the connection is
        dropped.
        """
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                     ("Host", "localhost"), ("Origin", "foo"),
                     ("Origin", "bar")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_noHostHeader(self):
        """
        If no I{Host} header is present, the connection is dropped.
        """
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                     ("Origin", "http://localhost/")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_multipleHostHeaders(self):
        """
        If more than one I{Host} header is present, the connection is
        dropped.
        """
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                     ("Origin", "http://localhost/"), ("Host", "foo"),
                     ("Host", "bar")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_missingHandler(self):
        """
        If no handler is registered for the given resource, the connection is
        dropped.
        """
        channel = self.renderRequest(url="/foo")
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_noConnectionUpgrade(self):
        """
        If the I{Connection: Upgrade} header is not present, the connection is
        dropped.
        """
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), ("Host", "localhost"),
                     ("Origin", "http://localhost/")])
        self.assertIn("404 Not Found", channel.transport.written.getvalue())


    def test_noUpgradeWebSocket(self):
        """
        If the I{Upgrade: WebSocket} header is not present, the connection is
        dropped.
        """
        channel = self.renderRequest(
            headers=[("Connection", "Upgrade"), ("Host", "localhost"),
                     ("Origin", "http://localhost/")])
        self.assertIn("404 Not Found", channel.transport.written.getvalue())


    def test_render(self):
        """
        If the handshake is successful, we can read back the server handshake,
        and the channel is setup for raw mode.
        """
        channel = self.renderRequest()
        self.assertTrue(channel.raw)
        self.assertEquals(
            channel.transport.written.getvalue(),
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "WebSocket-Origin: http://localhost/\r\n"
            "WebSocket-Location: ws://localhost/test\r\n\r\n")
        self.assertFalse(channel.transport.disconnected)

    def test_render_handShake76(self):
        """
        Test a hixie-76 handShake.
        """
        # we need to construct a challenge
        key1 = '1x0x0 0y00 0'  # 1000000
        key2 = '1b0b0 000 0'   # 1000000
        body = '12345678'
        headers = [
            ("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
            ("Host", "localhost"), ("Origin", "http://localhost/"),
            ("Sec-WebSocket-Key1", key1), ("Sec-WebSocket-Key2", key2)]
        channel = self.renderRequest(headers=headers, body=body)

        self.assertTrue(channel.raw)

        result = channel.transport.written.getvalue()

        headers, response = result.split('\r\n\r\n')

        self.assertEquals(
            headers,
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "Sec-WebSocket-Origin: http://localhost/\r\n"
            "Sec-WebSocket-Location: ws://localhost/test")

        # check challenge is correct
        from hashlib import md5
        import struct
        self.assertEquals(md5(struct.pack('>ii8s', 500000, 500000, body)).digest(), response)

        self.assertFalse(channel.transport.disconnected)

    def test_secureRender(self):
        """
        If the WebSocket connection is over SSL, the I{WebSocket-Location}
        header specified I{wss} as scheme.
        """
        channel = self.renderRequest(ssl=True)
        self.assertTrue(channel.raw)
        self.assertEquals(
            channel.transport.written.getvalue(),
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "WebSocket-Origin: http://localhost/\r\n"
            "WebSocket-Location: wss://localhost/test\r\n\r\n")
        self.assertFalse(channel.transport.disconnected)


    def test_frameReceived(self):
        """
        C{frameReceived} is called with the received frames after handshake.
        """
        handlers = []
        def handlerFactory(request):
            handler = TestHandler(request)
            handlers.append(handler)
            return handler
        self.site.addHandler("/test2", handlerFactory)
        channel = self.renderRequest(url="/test2")
        self.assertEquals(len(handlers), 1)
        handler = handlers[0]
        channel._transferDecoder.dataReceived("\x00hello\xff\x00boy\xff")
        self.assertEquals(handler.frames, ["hello", "boy"])


    def test_websocketProtocolAccepted(self):
        """
        The I{WebSocket-Protocol} header is echoed by the server if the
        protocol is among the supported protocols.
        """
        self.site.supportedProtocols.append("pixiedust")
        channel = self.renderRequest(
            headers = [
            ("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
            ("Host", "localhost"), ("Origin", "http://localhost/"),
            ("WebSocket-Protocol", "pixiedust")])
        self.assertTrue(channel.raw)
        self.assertEquals(
            channel.transport.written.getvalue(),
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "WebSocket-Origin: http://localhost/\r\n"
            "WebSocket-Location: ws://localhost/test\r\n"
            "WebSocket-Protocol: pixiedust\r\n\r\n")
        self.assertFalse(channel.transport.disconnected)


    def test_tooManyWebSocketProtocol(self):
        """
        If more than one I{WebSocket-Protocol} headers are specified, the
        connection is dropped.
        """
        self.site.supportedProtocols.append("pixiedust")
        channel = self.renderRequest(
            headers = [
            ("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
            ("Host", "localhost"), ("Origin", "http://localhost/"),
            ("WebSocket-Protocol", "pixiedust"),
            ("WebSocket-Protocol", "fairymagic")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_unsupportedProtocols(self):
        """
        If the I{WebSocket-Protocol} header specified an unsupported protocol,
        the connection is dropped.
        """
        self.site.supportedProtocols.append("pixiedust")
        channel = self.renderRequest(
            headers = [
            ("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
            ("Host", "localhost"), ("Origin", "http://localhost/"),
            ("WebSocket-Protocol", "fairymagic")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_queued(self):
        """
        Queued requests are unsupported, thus closed by the
        C{WebSocketSite}.
        """
        channel = self.renderRequest(queued=True)
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)


    def test_addHandlerWithoutSlash(self):
        """
        C{addHandler} raises C{ValueError} if the resource name doesn't start
        with a slash.
        """
        self.assertRaises(
            ValueError, self.site.addHandler, "test", TestHandler)
Example #19
0
 def __init__(self, resource, logPath=None, timeout=60 * 60 * 12,
              supportedProtocols=None):
     WebSocketSite.__init__(self, resource, logPath, timeout, supportedProtocols)
     self.presence = []
     print " ! SycometWebSocketFactory initiated"
Example #20
0
class WebSocketSiteTestCase(TestCase):
    """
    Tests for L{WebSocketSite}.
    """
    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/test", TestHandler)

    def renderRequest(self,
                      headers=None,
                      url="/test",
                      ssl=False,
                      queued=False,
                      body=None):
        """
        Render a request against C{self.site}, writing the WebSocket
        handshake.
        """
        if headers is None:
            headers = [("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                       ("Host", "localhost"), ("Origin", "http://localhost/")]
        channel = DummyChannel()
        if ssl:
            channel.transport = channel.SSL()
        channel.site = self.site
        request = self.site.requestFactory(channel, queued)
        for k, v in headers:
            request.requestHeaders.addRawHeader(k, v)
        request.gotLength(0)
        request.requestReceived("GET", url, "HTTP/1.1")
        if body:
            request.channel._transferDecoder.finishCallback(body)
        return channel

    def test_multiplePostpath(self):
        """
        A resource name can consist of several path elements.
        """
        handlers = []

        def handlerFactory(request):
            handler = TestHandler(request)
            handlers.append(handler)
            return handler

        self.site.addHandler("/foo/bar", handlerFactory)
        channel = self.renderRequest(url="/foo/bar")
        self.assertEquals(len(handlers), 1)
        self.assertFalse(channel.transport.disconnected)

    def test_queryArguments(self):
        """
        A resource name may contain query arguments.
        """
        handlers = []

        def handlerFactory(request):
            handler = TestHandler(request)
            handlers.append(handler)
            return handler

        self.site.addHandler("/test?foo=bar&egg=spam", handlerFactory)
        channel = self.renderRequest(url="/test?foo=bar&egg=spam")
        self.assertEquals(len(handlers), 1)
        self.assertFalse(channel.transport.disconnected)

    def test_noOriginHeader(self):
        """
        If no I{Origin} header is present, the connection is closed.
        """
        channel = self.renderRequest(
            headers=[("Upgrade",
                      "WebSocket"), ("Connection",
                                     "Upgrade"), ("Host", "localhost")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_multipleOriginHeaders(self):
        """
        If more than one I{Origin} header is present, the connection is
        dropped.
        """
        channel = self.renderRequest(headers=[(
            "Upgrade",
            "WebSocket"), ("Connection",
                           "Upgrade"), ("Host",
                                        "localhost"), ("Origin",
                                                       "foo"), ("Origin",
                                                                "bar")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_noHostHeader(self):
        """
        If no I{Host} header is present, the connection is dropped.
        """
        channel = self.renderRequest(
            headers=[("Upgrade",
                      "WebSocket"), ("Connection",
                                     "Upgrade"), ("Origin",
                                                  "http://localhost/")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_multipleHostHeaders(self):
        """
        If more than one I{Host} header is present, the connection is
        dropped.
        """
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), (
                "Connection",
                "Upgrade"), ("Origin",
                             "http://localhost/"), ("Host",
                                                    "foo"), ("Host", "bar")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_missingHandler(self):
        """
        If no handler is registered for the given resource, the connection is
        dropped.
        """
        channel = self.renderRequest(url="/foo")
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_noConnectionUpgrade(self):
        """
        If the I{Connection: Upgrade} header is not present, the connection is
        dropped.
        """
        channel = self.renderRequest(headers=[(
            "Upgrade",
            "WebSocket"), ("Host", "localhost"), ("Origin",
                                                  "http://localhost/")])
        self.assertIn("404 Not Found", channel.transport.written.getvalue())

    def test_noUpgradeWebSocket(self):
        """
        If the I{Upgrade: WebSocket} header is not present, the connection is
        dropped.
        """
        channel = self.renderRequest(
            headers=[("Connection",
                      "Upgrade"), ("Host",
                                   "localhost"), ("Origin",
                                                  "http://localhost/")])
        self.assertIn("404 Not Found", channel.transport.written.getvalue())

    def test_render(self):
        """
        If the handshake is successful, we can read back the server handshake,
        and the channel is setup for raw mode.
        """
        channel = self.renderRequest()
        self.assertTrue(channel.raw)
        self.assertEquals(
            channel.transport.written.getvalue(),
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "WebSocket-Origin: http://localhost/\r\n"
            "WebSocket-Location: ws://localhost/test\r\n\r\n")
        self.assertFalse(channel.transport.disconnected)

    def test_render_handShake76(self):
        """
        Test a hixie-76 handShake.
        """
        # we need to construct a challenge
        key1 = '1x0x0 0y00 0'  # 1000000
        key2 = '1b0b0 000 0'  # 1000000
        body = '12345678'
        headers = [("Upgrade", "WebSocket"), ("Connection", "Upgrade"),
                   ("Host", "localhost"), ("Origin", "http://localhost/"),
                   ("Sec-WebSocket-Key1", key1), ("Sec-WebSocket-Key2", key2)]
        channel = self.renderRequest(headers=headers, body=body)

        self.assertTrue(channel.raw)

        result = channel.transport.written.getvalue()

        headers, response = result.split('\r\n\r\n')

        self.assertEquals(
            headers, "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "Sec-WebSocket-Origin: http://localhost/\r\n"
            "Sec-WebSocket-Location: ws://localhost/test")

        # check challenge is correct
        from hashlib import md5
        import struct
        self.assertEquals(
            md5(struct.pack('>ii8s', 500000, 500000, body)).digest(), response)

        self.assertFalse(channel.transport.disconnected)

    def test_secureRender(self):
        """
        If the WebSocket connection is over SSL, the I{WebSocket-Location}
        header specified I{wss} as scheme.
        """
        channel = self.renderRequest(ssl=True)
        self.assertTrue(channel.raw)
        self.assertEquals(
            channel.transport.written.getvalue(),
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "WebSocket-Origin: http://localhost/\r\n"
            "WebSocket-Location: wss://localhost/test\r\n\r\n")
        self.assertFalse(channel.transport.disconnected)

    def test_frameReceived(self):
        """
        C{frameReceived} is called with the received frames after handshake.
        """
        handlers = []

        def handlerFactory(request):
            handler = TestHandler(request)
            handlers.append(handler)
            return handler

        self.site.addHandler("/test2", handlerFactory)
        channel = self.renderRequest(url="/test2")
        self.assertEquals(len(handlers), 1)
        handler = handlers[0]
        channel._transferDecoder.dataReceived("\x00hello\xff\x00boy\xff")
        self.assertEquals(handler.frames, ["hello", "boy"])

    def test_websocketProtocolAccepted(self):
        """
        The I{WebSocket-Protocol} header is echoed by the server if the
        protocol is among the supported protocols.
        """
        self.site.supportedProtocols.append("pixiedust")
        channel = self.renderRequest(
            headers=[("Upgrade",
                      "WebSocket"), ("Connection",
                                     "Upgrade"), ("Host", "localhost"),
                     ("Origin",
                      "http://localhost/"), ("WebSocket-Protocol",
                                             "pixiedust")])
        self.assertTrue(channel.raw)
        self.assertEquals(
            channel.transport.written.getvalue(),
            "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            "Upgrade: WebSocket\r\n"
            "Connection: Upgrade\r\n"
            "WebSocket-Origin: http://localhost/\r\n"
            "WebSocket-Location: ws://localhost/test\r\n"
            "WebSocket-Protocol: pixiedust\r\n\r\n")
        self.assertFalse(channel.transport.disconnected)

    def test_tooManyWebSocketProtocol(self):
        """
        If more than one I{WebSocket-Protocol} headers are specified, the
        connection is dropped.
        """
        self.site.supportedProtocols.append("pixiedust")
        channel = self.renderRequest(
            headers=[("Upgrade", "WebSocket"), (
                "Connection",
                "Upgrade"), ("Host",
                             "localhost"), ("Origin", "http://localhost/"),
                     ("WebSocket-Protocol",
                      "pixiedust"), ("WebSocket-Protocol", "fairymagic")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_unsupportedProtocols(self):
        """
        If the I{WebSocket-Protocol} header specified an unsupported protocol,
        the connection is dropped.
        """
        self.site.supportedProtocols.append("pixiedust")
        channel = self.renderRequest(
            headers=[("Upgrade",
                      "WebSocket"), ("Connection",
                                     "Upgrade"), ("Host", "localhost"),
                     ("Origin",
                      "http://localhost/"), ("WebSocket-Protocol",
                                             "fairymagic")])
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_queued(self):
        """
        Queued requests are unsupported, thus closed by the
        C{WebSocketSite}.
        """
        channel = self.renderRequest(queued=True)
        self.assertFalse(channel.transport.written.getvalue())
        self.assertTrue(channel.transport.disconnected)

    def test_addHandlerWithoutSlash(self):
        """
        C{addHandler} raises C{ValueError} if the resource name doesn't start
        with a slash.
        """
        self.assertRaises(ValueError, self.site.addHandler, "test",
                          TestHandler)
Example #21
0
                                                     command)
                print timers
            else:
                self.dispatch(data)

    def connectionMade(self):
        print 'Connected to client..',

    def connectionLost(self, reason):
        print 'Lost connection.'
        if self.authenticated:
            WebSockClients.remove(self)


root = static.File(WEBSITE_ROOT)
site = WebSocketSite(root)
site.addHandler('/ws', WSHandler)
#reactor.listenTCP(WEBSOCKET_PORT, site) #If you choose not to use wss, update index.html appropriately.
reactor.listenSSL(WEBSOCKET_PORT, site,
                  ssl.DefaultOpenSSLContextFactory(
                      SSL_PRIVKEY,
                      SSL_CERT,
                  ))
print "Web socket listening on port: ", WEBSOCKET_PORT

################################################################################
################################################################################

if __name__ == '__main__':

    # Start reactor:
Example #22
0
    def onBattleFinished(self, json):
        self.proxy.battleFinished(json['battleid'], json['result'])

class FlashSocketPolicy(Protocol):
    """ A simple Flash socket policy server.
    See: http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
    """
    def connectionMade(self):
        policy = '<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM ' \
                 '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">' \
                 '<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>'
        self.transport.write(policy)
        self.transport.loseConnection()



if __name__ == "__main__":
    # run our websocket server
    # serve index.html from the local directory
    root = File('.')
    site = WebSocketSite(root)
    site.addHandler('/test', POhandler)
    reactor.listenTCP(8080, site)
    # run policy file server
    #factory = Factory()
    #factory.protocol = FlashSocketPolicy
    #reactor.listenTCP(843, factory)
    reactor.run()

 def setUp(self):
     self.site = WebSocketSite(Resource())
     self.site.addHandler("/bar", TestHandlerWithExtensions)
     self.p = reactor.listenTCP(0, self.site, interface="127.0.0.1")
Example #24
0
        self.transport.write(data)

    def frameReceived(self, frame):
        print 'Peer: ', self.transport.getPeer()
        self.transport.write(frame)
        self.periodic_call.start(0.5)

    def connectionMade(self):
        print 'Connected to client.'
        # here would be a good place to register this specific handler
        # in a dictionary mapping some client identifier (like IPs) against
        # self (this handler object)

    def connectionLost(self, reason):
        print 'Lost connection.'
        self.periodic_call.stop()
        del self.periodic_call
        # here is a good place to deregister this handler object


if __name__ == "__main__":
    from twisted.internet import reactor

    # run our websocket server
    # serve index.html from the local directory
    root = File('.')
    site = WebSocketSite(root)
    site.addHandler('/test', Testhandler)
    reactor.listenTCP(8080, site)
    reactor.run()
            self.task.stop()
        # here is a good place to deregister this handler object


class Ticker(Thread):
    def __init__(self, port=9090):
        Thread.__init__(self)
        self.port = port
        
    def run(self):
        root = File('.')
        site = WebSocketSite(root)
        site.addHandler('/test', TickerHandler)
        print "\nWebSocket Server starts at %d" % self.port
        reactor.listenTCP(self.port, site)
        reactor.run(installSignalHandlers=0)

    def stop(self):
        print "Shutting down WebSocket Server\n"
        reactor.stop()


if __name__ == "__main__":
    # run our websocket server
    # serve index.html from the local directory
    root = File('.')
    site = WebSocketSite(root)
    site.addHandler('/test', TickerHandler)
    reactor.listenTCP(9090, site)
    reactor.run()
Example #26
0
        del self.periodic_call
        # here is a good place to deregister this handler object


class FlashSocketPolicy(Protocol):
    """ A simple Flash socket policy server.
    See: http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
    """
    def connectionMade(self):
        policy = '<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM ' \
                 '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">' \
                 '<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>'
        self.transport.write(policy)
        self.transport.loseConnection()


if __name__ == "__main__":
    from twisted.internet import reactor

    # run our websocket server
    # serve index.html from the local directory
    root = File('.')
    site = WebSocketSite(root)
    site.addHandler('/test', Testhandler)
    reactor.listenTCP(8080, site)
    # run policy file server
    factory = Factory()
    factory.protocol = FlashSocketPolicy
    reactor.listenTCP(843, factory)
    reactor.run()
Example #27
0
						if elapsed * 1000 > sub['delay']:
							socket.sendLatest(topic)
						else:
							if not ('futureSend' in sub and sub['futureSend'].active()):
								sub['futureSend'] = reactor.callLater(sub['delay'] / 1000.0 - elapsed, socket.sendLatest, topic)
			reactor.callFromThread(handle, msg)
		return handleMsg

	def run_ros_thread():
		def wait_for_exit():
			rospy.spin()
			reactor.stop()
		# don't use reactor.callInThread or we might clog the thread pool
		thread = Thread(target = wait_for_exit)
		# the ros thread won't stop on exit
		thread.setDaemon(True)
		thread.start()
	reactor.callWhenRunning(run_ros_thread)

	if docroot:
		root = File(docroot)
	else:
		root = Resource()
	if jsfile:
		root.putChild(jsfile, File(roslib.packages.resource_file('rosbridge', '', 'ros.js')))
	site = WebSocketSite(root)
	site.addHandler(wspath, wsHandlerFactory)
	# 50 is the default backlog size
	reactor.listenTCP(port, site, 50, host)
	reactor.run()
Example #28
0
 def setUp(self):
     self.site = WebSocketSite(Resource())
     self.site.addHandler("/test", TestHandler)
Example #29
0
            self.sendMessage(error='too many peers')
            self.transport.close()
        peers.append(self)
        if len(peers) == 2:
            peers[0].sendMessage(state='controlling')
            peers[1].sendMessage(state='controlled')
        else:
            self.sendMessage(state='waiting')
    
    def sendMessage(self, *msg, **kwargs):
        if kwargs:
            self.transport.write(json.dumps(kwargs))
        else:
            self.transport.write(json.dumps(msg[0]))
        
    def connectionLost(self, reason):
        print 'Lost connection.'
        # here is a good place to deregister this handler object
        global peers
        peers.remove(self)

if __name__ == '__main__':
    from twisted.internet import reactor

    # run our websocket server
    # serve index.html from the local directory
    root = File('.')
    site = WebSocketSite(root)
    site.addHandler('/offers', WebRTCOffersHandler)
    reactor.listenTCP(8080, site)
    reactor.run()
Example #30
0

if __name__ == "__main__":
    root = RootResource()

    # Mount the directories containing our static files
    staticDir = static.File("./static/")
    staticDir.putChild("algorithm", static.File("../algorithm/"))
    staticDir.directoryListing = lambda: error.ForbiddenResource()
    root.putChild("static", staticDir)

    # Create a resource that spawns new sessions as they are accessed
    root.putChild("session", SessionDispatcherResource())

    # Create a transport endpoint that can be accessed using a WebSocket
    site = WebSocketSite(root)
    site.addHandler("/transport", TransportHandler)

    # Start listening
    listener = reactor.listenTCP(PORT, site)

    print "EXPERIMENTAL SERVER - Do not use in production environments!"
    print "Read the README file before using this."
    print

    listeningHost = listener.getHost()
    print "Listening for HTTP connections on %s:%s" % (listeningHost.host,
                                                       listeningHost.port)
    print

    reactor.run()
class ClientTestCase(unittest.TestCase):
    """
    Base class for test cases
    """

    ServerHandlerClass = TestHandler
    simpleData = "bot"
    fragment = False

    def setUp(self):
        self.site = WebSocketSite(Resource())
        self.site.addHandler("/bar", self.ServerHandlerClass)
        self.p = reactor.listenTCP(0, self.site, interface="127.0.0.1")

        url = "ws://localhost:%d/bar" % self.p.getHost().port
        self.factory = TestClientFactory(url)
        reactor.connectTCP("127.0.0.1", self.p.getHost().port, self.factory)

    def tearDown(self):
        self.p.stopListening()

    def trace_lost_connection(self, reason):
        ## XXX: How to really _fail_ the test when using a deferred?
        log.logging.error("Test failed with unexpected error!" "Sorry I cannot get you the traceback")
        log.logging.error(reason.value)
        self.fail(reason.value)

    def clean_disconnection(self, reason):
        self.assertEqual(
            self.factory.responses,
            self.factory.expectedResponses,
            "Expected %d response(s), got %d" % (self.factory.expectedResponses, self.factory.responses),
        )
        self.assertEqual(
            len(self.factory.pongs),
            self.factory.expectedPongs,
            "Expected %d pong(s), got %d" % (self.factory.expectedPongs, len(self.factory.pongs)),
        )
        self.assertIsInstance(reason.value, ConnectionDone)

    def send(self, client, method=None, data=None):
        ## Client is got from the callback chain, actually ignored since it is
        ## already set to self.client by got_tcp_connection
        if not method:
            method = WebSocketClient.write
        if not data:
            data = self.simpleData
        self.sent_data = data
        kwargs = {}
        if self.fragment:
            ## Send first frame as fragmented, the next ones as continuation,
            ## plus one empty frame which is unfragmented
            nb_fragments = len(data) / self.fragment
            if nb_fragments > 0:
                for i, chunk in enumerate(chunks(data, self.fragment)):
                    if i != nb_fragments:
                        method.writeFragment(client, chunk, **kwargs)
                ## Final chunk: send with final flag
                method.writeFragment(client, chunk, final=True, **kwargs)
            else:
                ## When there's just one fragment, it will be interpreted
                ## as an unfragmented frame, so force sending it with
                ## final set to false plus an empty final fragment
                method.writeFragment(client, data, final=False, **kwargs)
                method.writeFragment(client, "", final=True, **kwargs)
        else:
            method(client, data, **kwargs)
        self.factory.client.write("END")
        return client

    def check_response(self, _):
        self.assertEqual("".join(self.factory.frames), self.sent_data)
        self.assertEqual(self.factory.client.subprotocol, None)