Пример #1
0
 def __init__(self, ack, sendDuration=0.01, respondDuration=0.01):
     self.ack = ack
     self.sendDuration = sendDuration
     self.respondDuration = respondDuration
     self.clients = set()
     self.factory = WebSocketServerFactory()
     self.factory.protocol = ServerProtocol
     self.factory.state = self
     LoopingCall(self.ping).start(2, now=False)
Пример #2
0
 def setUp(self):
     context = Context()
     server = makeTCPServer(context, MyServerProtocol,
                            WebSocketServerFactory())
     client = yield makeWebSocketClient(context, server)
     hook(WebSocketClientProtocol,
          'onMessage',
          decoder=lambda payload, _: payload)
     self.client = client.clientProtocol
     self.addCleanup(context.cleanup)
Пример #3
0
    def __init__(self, url, lookup, keyword=None):
        """

		:param factory: An instance of :class:`autobahn.twisted.websocket.WebSocketServerFactory`.
		:type factory: obj
		:param lookup: a function that accepts the keyword query parameter and returns a Transaction, or throws an exception if one wasn't found
		:type lookup: func
		:param keyword: the query parameter used to locate transactions
		:type keyword: string or None
		"""
        self._factory = WebSocketServerFactory(url)

        # disable autobahn http response for when someone hits websocket URI with no upgrade header
        # we just want to reject them with HTTP STATUS 426 (Need Upgrade)
        self._factory.setProtocolOptions(webStatus=False)

        self._factory.protocol = WebSocketConnection
        self.lookup = lookup
        self.keyword = keyword
Пример #4
0
def get_connection(game):
    """Provides a pretend conection object."""
    game.websocket_factory = WebSocketServerFactory()
    game.websocket_factory.game = game
    con = PretendConnection()
    con.factory = game.websocket_factory
    con.onOpen()
    game.connections.append(con)
    yield con
    game.connections.remove(con)
 def setUp(self):
     context = Context()
     server = makeTCPServer(context, WebSocketServerProtocol,
                            WebSocketServerFactory())
     hook(WebSocketServerProtocol,
          'onMessage',
          decoder=lambda payload, _: payload)
     client = yield makeWebSocketClient(context, server, MyClientProtocol)
     self.server = client.serverProtocol
     # cancel the loop:
     self.addCleanup(context.cleanup, delayedCalls=1)
Пример #6
0
    def __init__(self,
                 reactor,
                 threadpool,
                 publish_module,
                 websocket_ipc=None):
        self._reactor = reactor
        self._threadpool = threadpool
        self._publish_module = publish_module

        # ZMQ pubsub
        if websocket_ipc:
            path = ("ipc://" + os.path.abspath(websocket_ipc)).encode("utf-8")
            zf = ZmqFactory()
            e = ZmqEndpoint(ZmqEndpointType.bind, os.path.join(path))
            s = ZmqPubConnection(zf, e)
            global pub
            global pub_sock
            pub = s
            pub_sock = path

        # WebSockets
        factory = WebSocketServerFactory()
        factory.protocol = PubSubServerProtocol
        self.ws = CustomWebSocketResource(factory)
Пример #7
0
	def __init__(self, url, lookup, keyword=None):
		"""

		:param factory: An instance of :class:`autobahn.twisted.websocket.WebSocketServerFactory`.
		:type factory: obj
		:param lookup: a function that accepts the keyword query parameter and returns a Transaction, or throws an exception if one wasn't found
		:type lookup: func
		:param keyword: the query parameter used to locate transactions
		:type keyword: string or None
		"""
		self._factory = WebSocketServerFactory(url)
		
		# disable autobahn http response for when someone hits websocket URI with no upgrade header
		# we just want to reject them with HTTP STATUS 426 (Need Upgrade)
		self._factory.setProtocolOptions(webStatus=False)
		
		self._factory.protocol = WebSocketConnection
		self.lookup = lookup
		self.keyword = keyword
Пример #8
0
    def start_anydex(self, options):
        """
        Main method to startup AnyDex.
        """
        config = get_anydex_configuration()

        if options["statedir"]:
            # If we use a custom state directory, update various variables
            for key in config["keys"]:
                key["file"] = os.path.join(options["statedir"], key["file"])

            for community in config["overlays"]:
                if community["class"] == "TrustChainCommunity":
                    community["initialize"]["working_directory"] = options["statedir"]

        if 'testnet' in options and options['testnet']:
            for community in config["overlays"]:
                if community["class"] == "TrustChainCommunity":
                    community["class"] = "TrustChainTestnetCommunity"

        self.ipv8 = IPv8(config, enable_statistics=options['statistics'])

        def signal_handler(sig, _):
            msg("Received shut down signal %s" % sig)
            if not self._stopping:
                self._stopping = True
                if self.restapi:
                    self.restapi.stop()
                self.ipv8.stop()

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        msg("Starting AnyDex")

        if not options['no-rest-api']:
            self.restapi = RESTManager(self.ipv8)
            reactor.callLater(0.0, self.restapi.start)

            factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
            factory.protocol = AnyDexWebsocketProtocol
            reactor.listenTCP(9000, factory)

        # Get Trustchain + DHT overlays
        for overlay in self.ipv8.overlays:
            if isinstance(overlay, TrustChainTestnetCommunity):
                self.trustchain = overlay
            elif isinstance(overlay, DHTDiscoveryCommunity):
                self.dht = overlay

        # Initialize wallets
        dummy_wallet1 = DummyWallet1()
        self.wallets[dummy_wallet1.get_identifier()] = dummy_wallet1

        dummy_wallet2 = DummyWallet2()
        self.wallets[dummy_wallet2.get_identifier()] = dummy_wallet2

        # Load market community
        self.market = MarketTestnetCommunity(self.trustchain.my_peer, self.ipv8.endpoint, self.ipv8.network,
                                             trustchain=self.trustchain,
                                             dht=self.dht,
                                             wallets=self.wallets,
                                             working_directory=options["statedir"],
                                             record_transactions=False)

        self.ipv8.overlays.append(self.market)
        self.ipv8.strategies.append((RandomWalk(self.market), 20))
Пример #9
0
 def __init__(self, uri):
     WebSocketServerFactory.__init__(self, uri)
     self.clients = []
     self.users = {}
     self.sendTimeLoop()
Пример #10
0
class WebSocketResource(object):
    """
	A Twisted Web resource for WebSocket.
	"""
    isLeaf = True

    def __init__(self, url, lookup, keyword=None):
        """

		:param factory: An instance of :class:`autobahn.twisted.websocket.WebSocketServerFactory`.
		:type factory: obj
		:param lookup: a function that accepts the keyword query parameter and returns a Transaction, or throws an exception if one wasn't found
		:type lookup: func
		:param keyword: the query parameter used to locate transactions
		:type keyword: string or None
		"""
        self._factory = WebSocketServerFactory(url)

        # disable autobahn http response for when someone hits websocket URI with no upgrade header
        # we just want to reject them with HTTP STATUS 426 (Need Upgrade)
        self._factory.setProtocolOptions(webStatus=False)

        self._factory.protocol = WebSocketConnection
        self.lookup = lookup
        self.keyword = keyword

    # noinspection PyUnusedLocal
    def getChildWithDefault(self, name, request):
        """
		This resource cannot have children, hence this will always fail.
		"""
        return NoResource("No such child resource.")

    def putChild(self, path, child):
        """
		This resource cannot have children, hence this is always ignored.
		"""

    def render(self, request):
        """
		Render the resource. This will takeover the transport underlying
		the request, create a :class:`autobahn.twisted.websocket.WebSocketServerProtocol`
		and let that do any subsequent communication.
		"""
        # Create Autobahn WebSocket protocol.
        #
        protocol = self._factory.buildProtocol(request.transport.getPeer())

        if (not protocol):
            # If protocol creation fails, we signal "internal server error"
            request.setResponseCode(500)
            return b""

        # locate the transaction
        try:
            transaction = self.lookup(request.args[self.keyword][0] if (
                self.keyword is not None and request.args.has_key(self.keyword)
            ) else None)
        except:
            # failed to locate
            request.setResponseCode(400)
            return b""

        # Take over the transport from Twisted Web
        #
        transport, request.transport = request.transport, None

        transport.protocol = protocol
        protocol.makeConnection(transport)

        if (PY3):
            data = request.method + b' ' + request.uri + b' HTTP/1.1\x0d\x0a'

            for h in request.requestHeaders.getAllRawHeaders():
                data += h[0] + b': ' + b",".join(h[1]) + b'\x0d\x0a'

            data += b"\x0d\x0a"
            data += request.content.read()
        else:
            data = "%s %s HTTP/1.1\x0d\x0a" % (request.method, request.uri)

            for h in request.requestHeaders.getAllRawHeaders():
                data += "%s: %s\x0d\x0a" % (h[0], ",".join(h[1]))

            data += "\x0d\x0a"

        transaction.adoptWebSocket(protocol)

        protocol.dataReceived(data)

        return NOT_DONE_YET
Пример #11
0
class WebSocketResource(object):
	"""
	A Twisted Web resource for WebSocket.
	"""
	isLeaf = True

	def __init__(self, url, lookup, keyword=None):
		"""

		:param factory: An instance of :class:`autobahn.twisted.websocket.WebSocketServerFactory`.
		:type factory: obj
		:param lookup: a function that accepts the keyword query parameter and returns a Transaction, or throws an exception if one wasn't found
		:type lookup: func
		:param keyword: the query parameter used to locate transactions
		:type keyword: string or None
		"""
		self._factory = WebSocketServerFactory(url)
		
		# disable autobahn http response for when someone hits websocket URI with no upgrade header
		# we just want to reject them with HTTP STATUS 426 (Need Upgrade)
		self._factory.setProtocolOptions(webStatus=False)
		
		self._factory.protocol = WebSocketConnection
		self.lookup = lookup
		self.keyword = keyword

	# noinspection PyUnusedLocal
	def getChildWithDefault(self, name, request):
		"""
		This resource cannot have children, hence this will always fail.
		"""
		return NoResource("No such child resource.")

	def putChild(self, path, child):
		"""
		This resource cannot have children, hence this is always ignored.
		"""

	def render(self, request):
		"""
		Render the resource. This will takeover the transport underlying
		the request, create a :class:`autobahn.twisted.websocket.WebSocketServerProtocol`
		and let that do any subsequent communication.
		"""
		# Create Autobahn WebSocket protocol.
		#
		protocol = self._factory.buildProtocol(request.transport.getPeer())

		if(not protocol):
			# If protocol creation fails, we signal "internal server error"
			request.setResponseCode(500)
			return b""

		# locate the transaction
		try:
			transaction = self.lookup(request.args[self.keyword][0] if (self.keyword is not None and request.args.has_key(self.keyword)) else None)
		except:
			# failed to locate
			request.setResponseCode(400)
			return b""

		# Take over the transport from Twisted Web
		#
		transport, request.transport = request.transport, None

		transport.protocol = protocol
		protocol.makeConnection(transport)

		if(PY3):
			data = request.method + b' ' + request.uri + b' HTTP/1.1\x0d\x0a'

			for h in request.requestHeaders.getAllRawHeaders():
				data += h[0] + b': ' + b",".join(h[1]) + b'\x0d\x0a'

			data += b"\x0d\x0a"
			data += request.content.read()
		else:
			data = "%s %s HTTP/1.1\x0d\x0a" % (request.method, request.uri)

			for h in request.requestHeaders.getAllRawHeaders():
				data += "%s: %s\x0d\x0a" % (h[0], ",".join(h[1]))

			data += "\x0d\x0a"

		transaction.adoptWebSocket(protocol)

		protocol.dataReceived(data)

		return NOT_DONE_YET