Esempio n. 1
0
def main(argv):
    if len(argv) < 2: sys.exit(usage)
    loop = asyncio.get_event_loop()

    if argv[1] == "server":
        coro = playground.getConnector(
            "lab2_protocol").create_playground_server(ServerProtocol, 8000)
    else:
        if len(argv) < 3: sys.exit(usage)
        packet = DataPacket(data=argv[2].encode("utf8"))
        if len(argv) > 3: packet.id = int(argv[3])

        def callback(token, result):
            if result is None:
                print("Token is {}".format(token))
            else:
                print("Same" if result else "Not same / Not found")
            loop.stop()

        coro = playground.getConnector(
            "lab2_protocol").create_playground_connection(
                lambda: ClientProtocol(packet, callback), argv[1], 8000)

    asyncio.ensure_future(coro)
    loop.run_forever()
    loop.close()
Esempio n. 2
0
    async def start(self):
        self.updateAvailableServers()
        self.tracker.registerListener(self.notifyNewServer)

        # python does not have real closures. we have to do this ugly thing
        # to make the labmdas work in the callback
        closure = lambda c_codeId, c_oneShotClient: lambda future: self.pickleBack(c_codeId, future, c_oneShotClient)

        while not self.finished():
            nextServer = None
            while len(self.__serversAvailable) == 0:
                await self.__serverAvailableCondition.awaitCondition(lambda: len(self.__serversAvailable) > 0)
                if self.finished(): break
            nextServer = self.__serversAvailable.pop(0)
            
            # check the connector for the mobile code server
            connector = self.__addrData[nextServer].connector
            if not connector: continue
            try:
               playground.getConnector(connector)
            except:
               logger.debug("No such connector {}".format(connector))
               continue 
            
            #Get the code to run
            mobileCode, codeId = self.getNextCodeUnit(nextServer)
            if mobileCode:
                address, port = nextServer
                oneShotClient = MobileCodeClient(connector, address, port, mobileCode, 
                                                 self.auth,  self.wallet)
                # MobileCodeClient(connector, address, port, mobileCode, auth, wallet)
                result = oneShotClient.run()
                result.add_done_callback(closure(codeId, oneShotClient))
            else:
                logger.debug("Mobile code null for server {}".format(nextServer))
Esempio n. 3
0
def protocolController():
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    client = Protocol.ForgotPasswordClientProtocol()
    server = Protocol.ForgotPasswordServerProtocol()
    serv = playground.getConnector().create_playground_server(
        lambda: server, 8080)
    s = loop.run_until_complete(serv)
    print("Echo server running at {}".format(s.sockets[0].gethostname()))
    cli = playground.getConnector().create_playground_connection(
        lambda: client, "20174.1.1.1", 8080)
    transport, protocol = loop.run_until_complete(cli)
    print("Echo client running with t:{}. p:{}".format(transport, protocol))
    loop.run_forever()
    loop.close()
Esempio n. 4
0
def basicUnitTest():
    echoArgs = {}

    args = sys.argv[1:]
    i = 0
    for arg in args:
        if arg.startswith("-"):
            k, v = arg.split("=")
            echoArgs[k] = v
        else:
            echoArgs[i] = arg
            i += 1

    if not 0 in echoArgs:
        sys.exit("1")

    fclient = StackingProtocolFactory(lambda: PassThroughc1(),
                                      lambda: PassThroughc2())
    ptConnectorclient = playground.Connector(protocolStack=fclient)
    playground.setConnector("passthroughclient", ptConnectorclient)

    fserver = StackingProtocolFactory(lambda: PassThroughs1(),
                                      lambda: PassThroughs2())
    ptConnectorserver = playground.Connector(protocolStack=fserver)
    playground.setConnector("passthroughserver", ptConnectorserver)

    mode = echoArgs[0]
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)

    if mode.lower() == "server":
        coro = playground.getConnector(
            'passthroughserver').create_playground_server(
                lambda: MyProtocolServer(), 101)
        server = loop.run_until_complete(coro)
        print("my Server Started at {}".format(
            server.sockets[0].gethostname()))
        loop.run_forever()
        loop.close()

    else:
        address = mode
        coro = playground.getConnector(
            'passthroughclient').create_playground_connection(
                lambda: MyProtocolClient("hello", loop), address, 101)
        loop.run_until_complete(coro)
        loop.run_forever()
        loop.close()
    def __init__(self,
                 bankstackfactory,
                 username,
                 pw,
                 myaccount,
                 merchantaccount,
                 bankaddr=BANK_FIXED_PLAYGROUND_ADDR,
                 bankport=BANK_FIXED_PLAYGROUND_PORT):
        self._loginName = username
        self._pw = pw
        self.__bankAddr = bankaddr
        self.__bankPort = bankport
        self.__srcPaymentAccount = myaccount
        self.__destPaymentAccount = merchantaccount

        self.__d = None

        self.__asyncLoop = asyncio.get_event_loop()

        # Immediately connect to the bank (Should we wait for something instead?)
        coro = playground.getConnector().create_playground_connection(
            bankstackfactory, self.__bankAddr, self.__bankPort)
        fut = asyncio.run_coroutine_threadsafe(coro, self.__asyncLoop)
        fut.add_done_callback(self.__handleClientConnection)
        debugPrint("PayingClientWallet initialized!")
Esempio n. 6
0
def basicClientTest():
    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_connection(
        lambda: EchoClientProtocol(), '20174.1.1.1', 8888)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
Esempio n. 7
0
 def addCarToList(self, carid):
     self.__GPSCarList.append(carid)
     c = playground.getConnector()
     coro = c.create_playground_connection(
         lambda: self.addGpsSubscriber(carid), GPS_BROADCAST_ADDRESS,
         100 + carid)
     asyncio.get_event_loop().create_task(coro)
Esempio n. 8
0
def test():
    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_connection(
        lambda: StudentClient(), '20174.1.1.1', 8000)
    #coro = loop.create_connection(lambda: StudentClient(), '127.0.0.1', 8000)
    loop.run_until_complete(coro)
    #loop.run_forever()
    loop.close()
Esempio n. 9
0
def create_connection(protocol_factory, host, port, family=None, *args, **kargs):
    if args or kargs:
        raise Exception("Playground's create_connection does not support any arguments other than host, port, and family")
    if family == None and host is not None and "://" in host:
        family, host = host.split("://")
    elif family == None:
        family = "default"
    return playground.getConnector(family).create_playground_connection(protocol_factory, host, port)
Esempio n. 10
0
def server_run():

    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_server(
        lambda: ServerProtocol(), 101)
    server = loop.run_until_complete(coro)
    print("Echo Server Started at {}".format(server.sockets[0].gethostname()))
    loop.run_forever()
    loop.close()
Esempio n. 11
0
def basicUnitTest():
    echoArgs = {}

    args = sys.argv[1:]
    i = 0
    for arg in args:
        if arg.startswith("-"):
            k, v = arg.split("=")
            echoArgs[k] = v
        else:
            echoArgs[i] = arg
            i += 1

    if 0 not in echoArgs:
        sys.exit("1")

    fclient = StackingProtocolFactory(lambda: PassThroughc1(), lambda: PassThroughc2())
    fserver = StackingProtocolFactory(lambda: PassThroughs1(), lambda: PassThroughs2())

    lab2Connector = playground.Connector(protocolStack=(
        fclient,
        fserver))
    playground.setConnector("lab2_protocol", lab2Connector)

    mode = echoArgs[0]
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)

    if mode.lower() == "server":
        coro = playground.getConnector('lab2_protocol').create_playground_server(lambda: MyProtocolServer(), 101)
        server = loop.run_until_complete(coro)
        print("my Server Started at {}".format(server.sockets[0].gethostname()))
        loop.run_forever()
        loop.close()


    else:
        address = mode
        coro = playground.getConnector('lab2_protocol').create_playground_connection(
            lambda: MyProtocolClient("hello", loop),
            address, 101)
        loop.run_until_complete(coro)
        loop.run_forever()
        loop.close()
Esempio n. 12
0
 def __connect(self, cookie):
     # Immediately connect to the bank (Should we wait for something instead?)
     debugPrint("In __connect")
     coro = playground.getConnector(
         self.__connector).create_playground_connection(
             self.__bankFactory, self.__bankAddr, self.__bankPort)
     fut = asyncio.run_coroutine_threadsafe(coro, self.__asyncLoop)
     fut.add_done_callback(
         partial(self.__handleClientConnection, cookie=cookie))
     debugPrint("PayingClientWallet initialized!")
 def sendPing(self):
     if self._pinger == None:
         self._pinger = self.PingProtocol(self.receivePong)
         coro = playground.getConnector().create_playground_connection(
             lambda: self._pinger, "0.0.0.0", 60000)
         get_event_loop().create_task(coro)
     else:
         self._pinger.send()
     if self._scan:
         get_event_loop().call_later(25, self.sendPing)
Esempio n. 14
0
def basicUnitTest():

    loop = asyncio.get_event_loop()
    playground.getConnector().create_playground_server(
        lambda: EchoServerProtocol(), 8000)
    playground.getConnector().create_playground_connection(
        lambda: EchoClientProtocol(), "20174.1.1.1", 8000)
    client = EchoClientProtocol()  # Initialize Client Protocol
    server = EchoServerProtocol()  # Initialize Server Protocol
    cTransport, sTransport = MockTransportToProtocol.CreateTransportPair(
        client, server)

    #transportToServer = MockTransportToProtocol(server)
    #transportToClient = MockTransportToProtocol(client)
    packet1 = AccessResource()
    packet1Bytes = packet1.__serialize__()
    server.connection_made(sTransport)
    client.connection_made(cTransport)
    server.data_received(packet1Bytes)
Esempio n. 15
0
def basicOperation(mode, run = 1):
	loop = asyncio.get_event_loop()

	if mode == "server":
		#
		# Changing over to create_playground_server() seems to cause
		# some unexplained packet loss.
		#
		coroServer = playground.getConnector().create_playground_server(lambda: SimpleMathProtocolServer(), 8080)
		server = loop.run_until_complete(coroServer)

	else:
		coroClient = playground.getConnector().create_playground_connection(lambda: SimpleMathProtocolClient(), "20174.1.1.1", 8080)
		transport, protocol = loop.run_until_complete(coroClient)

		for i in range(0, int(run)):
			protocol.requestProblem()

	loop.run_forever()
	loop.close()
Esempio n. 16
0
def basicUnitTest():
    f = StackingProtocolFactory(lambda: PassThrough1(), lambda: PassThrough2())
    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)

    loop = asyncio.get_event_loop()
    coro = playground.getConnector('passthrough').create_playground_connection(
        lambda: StudentClient(), '20174.1.1.1', 8000)

    transport, protocol = loop.run_until_complete(coro)
    protocol.request(stdInCallback)
    loop.close()
Esempio n. 17
0
def server_run(): 

		f = StackingProtocolFactory(lambda: PassThrough1(), lambda: PassThrough2())
		ptConnector = playground.Connector(protocolStack=f)
		playground.setConnector("passthrough", ptConnector)	

		loop = asyncio.get_event_loop()
		coro = playground.getConnector('passthrough').create_playground_server(lambda: ServerProtocol(), 101)
		server = loop.run_until_complete(coro)
		print("Echo Server Started at {}".format(server.sockets[0].gethostname()))
		loop.run_forever()
		loop.close()
Esempio n. 18
0
def client_run():

	loopC = asyncio.get_event_loop()
	control = ClientProtocol()
	coroC = playground.getConnector().create_playground_connection(control.buildProtocol,'20174.1.1.1',101)
	transport,protocol = loopC.run_until_complete(coroC)
	print("Client Connected. Starting UI t:{}. p:{}".format(transport, protocol))
	#control.connection_made(transport)
	control.setTransport(transport)
	pkt1 = DB_connect()
	control.sendpacket(pkt1)
	loopC.run_forever()
	loopC.close()
Esempio n. 19
0
def lab_1e_test():
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    f = StackingProtocolFactory(lambda: higherProtocol1(), lambda: higherProtocol2())

    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)
    coro = playground.getConnector('passthrough').create_playground_server(lambda:MyServerProtocol(), 46427)
    server = loop.run_until_complete(coro)
    print('Serving on {}'.format(server.sockets[0].gethostname()))
    loop.run_forever()
    server.close()
    loop.close()
Esempio n. 20
0
 def transition(self, newState):
     if self.state == [StatelessClient.STATE_ERROR or StatelessClient.STATE_CLOSED]:
         raise Exception("Cannot transition out of state {}".self.state)
     self.state = newState
     
     if self.state == StatelessClient.STATE_CLOSED:
         self.resultFuture.set_result(self.finalResult)
         
     else:
     
         client = StatelessClient(self, self.auth, self.wallet)
         coro = playground.getConnector(self.connector).create_playground_connection(lambda: client, self.address, self.port)
         get_event_loop().create_task(coro)
Esempio n. 21
0
def basicUnitTest():
    echoArgs = {}

    args = sys.argv[1:]
    i = 0
    for arg in args:
        if arg.startswith("-"):
            k, v = arg.split("=")
            echoArgs[k] = v
        else:
            echoArgs[i] = arg
            i += 1

    if not 0 in echoArgs:
        sys.exit("1")

    mode = echoArgs[0]
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)

    if mode.lower() == "server":
        coro = playground.getConnector().create_playground_server(lambda: MyProtocolServer(), 101)
        server = loop.run_until_complete(coro)
        print("Echo Server Started at {}".format(server.sockets[0].gethostname()))
        loop.run_forever()
        loop.close()


    else:
        address = mode
        coro = playground.getConnector().create_playground_connection(lambda: MyProtocolClient("hello", loop),
                                                                      address, 101)
        #coro = loop.create_connection(lambda: MyProtocolClient("hello", loop),
        #                              '127.0.0.1', 8888)
        loop.run_until_complete(coro)
        loop.run_forever()
        loop.close()
Esempio n. 22
0
def main():
    from playground.common.logging import EnablePresetLogging, PRESET_DEBUG
    EnablePresetLogging(PRESET_DEBUG)

    args = sys.argv[1:]
    if len(args) != 4:
        print("Incorrect number of arguments (got %s, expected 4)" % len(args))
        print(
            "USAGE:\n\tpython3 bank_functional1.py [Bank Cert Path] [User Login Name]\n\t\t[Client/Requester Bank Account Name] [Server/Merchant Bank Account Name]"
        )
        return

    bankcert = loadCertFromFile(args[0])
    username = args[1]
    pw = getpass.getpass("Enter client/requester's bank password: "******"print('this is a test')"
    fee = 1
    #debugPrint("Creating NullServerWallet")
    #serverWallet = NullServerWallet()
    debugPrint("Creating PayingServerWallet")
    serverWallet = PayingServerWallet(bankcert, merchantaccount)
    debugPrint("Creating SimplePayingServerAuth")
    serverAuth = SimplePayingServerAuth(fee)
    debugPrint("Creating DefaultMobileCodeEngine")
    serverEngine = DefaultMobileCodeEngine()

    # debugPrint("Creating NullClientWallet")
    # clientWallet = NullClientWallet()
    debugPrint("Creating PayingClientWallet")
    clientWallet = PayingClientWallet(bankstackfactory, username, pw,
                                      payeraccount, merchantaccount)

    def serverFactory():
        debugPrint("Factory creating MobileCodeServer")
        return MobileCodeServer(serverWallet, serverAuth, serverEngine)

    debugPrint("Creating MobileCodeClient")
    client = MobileCodeClient("default", "localhost", 1, samplecode,
                              SimplePayingClientAuth(), clientWallet)
    coro = playground.getConnector().create_playground_server(serverFactory, 1)
    loop = get_event_loop()
    server = loop.run_until_complete(coro)
    print("Server started")
    loop.call_later(0, RunCodeAndPrintResult, client)
    loop.run_forever()
Esempio n. 23
0
def basicServerTest():
    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_server(
        lambda: EchoServerProtocol(), 8888)
    server = loop.run_until_complete(coro)

    print("Serving on ...")
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()
Esempio n. 24
0
def test():
    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_server(
        lambda: QuizServer(), 8000)
    #coro = loop.create_server(QuizServer, '127.0.0.1', 8000)
    server = loop.run_until_complete(coro)

    print('Serving on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()
Esempio n. 25
0
def lab_1e_test():
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    f = StackingProtocolFactory(lambda: higherProtocol1(),
                                lambda: higherProtocol2())

    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)
    #message = 'Hello World!'
    myconnect = playground.getConnector(
        'passthrough').create_playground_connection(lambda: MyClientProtocol(),
                                                    '20174.1.1.1', 46427)
    transport, client = loop.run_until_complete(myconnect)
    pktCR = ConnectionRequest()
    client.send(pktCR)
    loop.run_forever()
    loop.close()
Esempio n. 26
0
def basicUnitTest():

    f = StackingProtocolFactory(lambda: PassThrough1(), lambda: PassThrough2())
    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)

    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    coro = playground.getConnector('passthrough').create_playground_server(
        lambda: QuizServer(), 8000)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()
Esempio n. 27
0
def client_run():

    f = StackingProtocolFactory(lambda: PassThrough1(), lambda: PassThrough2())
    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)
    control = ClientProtocol()
    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_connection(
        control.buildProtocol, '20174.1.1.1', 101)
    transport, protocol = loop.run_until_complete(coro)

    print("Client Connected. Starting UI t:{}. p:{}".format(
        transport, protocol))

    #control.connection_made(transport)
    control.setTransport(transport)
    pkt1 = DB_connect()
    control.sendpacket(pkt1)

    loop.run_forever()
    loop.close()
Esempio n. 28
0
    def __init__(self,x,y,devid,maxv,destx,desty,trafficmap,cs):
        trafficDevice.__init__(self,x,y,devid)
        self.__maxVelocity = maxv
        self.__velocity = 0
        self.__destPosX = destx
        self.__destPosY = desty
        self.__arriveDest = 0
        self.__carPath = []#item is string as (x,y)
        self.__statusList = []
        self.__curPosInPath = 0
        self.__curCycle = -1
        self.__myMap = deepcopy(trafficmap)#Only contains the blank map, receives message from other cars within its sight.
        self.__mapSize = len(self.__myMap[0])
        self.__findCarPath()
        self.__ifCrash = 0
        self.__ifDestReachable = 1
        self.__networkType = "GPS"
        self.__checkGPSSignature = cs

        self.__gpsReceiver = GPSListener(self.__checkGPSSignature)
        #print("Creating playground server fro device ID {}".format(devid))
        coro = playground.getConnector().create_playground_server(lambda: self.__gpsReceiver, host="255.255.255.255", sourcePort=100+devid)
        asyncio.get_event_loop().create_task(coro)
Esempio n. 29
0
        print("At the Client")
        self.deserializer.update(data)
        for pkt in self.deserializer.nextPackets():
            if isinstance(pkt, Challenge):
                print("Challenge Received")
                self.transport.write(sendAuthentication())
            elif isinstance(pkt, Connection):
                print("Client received: Server says: {}".format(
                    pkt.confirmation))
            else:
                connection_lost(self)

    def connection_lost(self, exc):
        self.transport = None


class EchoControl:
    def buildProtocol(self):
        return MyClientProtocol()


loop = asyncio.get_event_loop()
conn = EchoControl()
coro = playground.getConnector().create_playground_connection(
    conn.buildProtocol, "2020.20.2.2", 101)
#coro = loop.create_connection(lambda:MyClientProtocol(), "127.0.0.1", 27122)
client = loop.run_until_complete(coro)
print("Echo Client Connected.")
loop.run_forever()
loop.close()
def basicUnitTest():
    print(
        "WARNING: Since most of the data only exist in transmission, this unit test will use printing method to show if the code works"
    )
    print("")
    asyncio.set_event_loop(TestLoopEx())
    clientName = "peter"
    tableNumber = 14
    stockList = {
        "Appetizers": {
            "Buffalo Fried Cauliflower": 43,
            "Triple Dipper": 37
        },
        "Sandwiches": {
            "Bacon Avocado Chicken": 96,
            "Buffalo Chicken Ranch": 23,
            "Grilled Chicken": 3
        },
        "Salads_and_Soups": {
            "Santa Fe Crisper Salad": 54,
            "Margherita Flatbread Salad": 42,
            "Margherita Flatbread Salad with Chicken": 32,
            "House Salad": 35
        },
        "Desert": {
            "Triple Berry Crumble Cake": 1
        }
    }
    menu = {
        "Appetizers": ["Buffalo Fried Cauliflower", "Triple Dipper"],
        "Sandwiches":
        ["Bacon Avocado Chicken", "Buffalo Chicken Ranch", "Grilled Chicken"],
        "Salads_and_Soups": [
            "Santa Fe Crisper Salad", "Margherita Flatbread Salad",
            "Margherita Flatbread Salad with Chicken", "House Salad"
        ],
        "Desert": ["Triple Berry Crumble Cake"]
    }
    client = playground.getConnector().create_playground_server(
        lambda: CustomerClientProtocol(clientName, tableNumber), 101)
    server = playground.getConnector().create_playground_connection(
        lambda: RestaurantServerProtocol(stockList, menu), "20174.1.1.1", 101)
    # client = CustomerClientProtocol(clientName, tableNumber)
    # server = RestaurantServerProtocol(stockList, menu)
    transportToServer = MockTransportToProtocol(server)
    transportToClient = MockTransportToProtocol(client)
    transportToServer.setRemoteTransport(transportToClient)
    transportToClient.setRemoteTransport(transportToServer)
    client.connection_made(transportToServer)
    server.connection_made(transportToClient)
    print(
        "======================================================================"
    )
    print("Submission: Testing sending menu...")
    client.requestMenu()
    assert menu.keys() == client.receivedMenu.keys()
    for key in menu.keys():
        assert menu[key] == client.receivedMenu[key]
        assert client.receivedMenu[key] == server.originalMenu[key]
    assert client.status == client.SEND_ORDER
    assert server.status == server.WAITING_ORDER
    print(
        "======================================================================"
    )
    print("Submission: Testing sending order from Client...")

    print("1) Testing normal orders...(should success)")
    ordered = {
        "Bacon Avocado Chicken": 1,
        "Buffalo Chicken Ranch": 2,
        "Buffalo Fried Cauliflower": 1
    }
    client.sendOrder(ordered)
    assert client.status == client.WAITING
    assert server.status == server.WAITING
    print(" ")
    print(
        "2) Testing ordering dishes that does not exist in menu...(should fail)"
    )
    client.requestMenu()
    ordered = {
        "Bacon Avocado Chicken": 1,
        "Buffalo Chicken Ranch": 2,
        "Buffalo Fried Cauliflower": 1,
        "Something not exist1": 10,
        "Something not exist3": 12
    }
    client.sendOrder(ordered)
    print(" ")
    print("3) Testing ordering dishes that are out of stock...(should fail)")
    client.requestMenu()
    ordered = {
        "Bacon Avocado Chicken": 1,
        "Buffalo Chicken Ranch": 2,
        "Triple Berry Crumble Cake": 3,
        "Grilled Chicken": 4
    }
    client.sendOrder(ordered)
    print(" ")
    print(
        "4) Testing ordering dishes that are both not exist and out of stock...(should fail)"
    )
    client.requestMenu()
    ordered = {
        "Bacon Avocado Chicken": 1,
        "Buffalo Chicken Ranch": 2,
        "Triple Berry Crumble Cake": 3,
        "Grilled Chicken": 4,
        "Something not exist1": 10,
        "Something not exist3": 12
    }
    client.sendOrder(ordered)
    print(" ")
    print("5) Testing ordering nothing")
    client.requestMenu()
    client.sendOrder({})
    print(
        "======================================================================"
    )
Esempio n. 31
0
		highertransport = StackingTransport(self.transport)
		self.higherProtocol().connection_made(highertransport)

	def data_received(self,data):
		self.higherProtocol().data_received(data)
	
	def connection_lost(self,exc):
		pass
		# self.highertrasnport = None



name = sys.argv[1]
loop = asyncio.get_event_loop()
loop.set_debug(enabled = True)
f = StackingProtocolFactory(lambda:passThrough1(),lambda:passThrough2())
ptConnector = playground.Connector(protocolStack=f)
playground.setConnector("passthrough",ptConnector)

if name == "server":
	coro = playground.getConnector('passthrough').create_playground_server(lambda: ServerProtocol(), 8888)
	server = loop.run_until_complete(coro)
	print("Echo Server Started at {}".format(server.sockets[0].gethostname()))
	loop.run_forever()
	loop.close()
else:
	coro = playground.getConnector('passthrough').create_playground_connection(lambda: ClientProtocol(packet2, loop),"20174.1.1.1",8888)
	transport, protocol = loop.run_until_complete(coro)
	print("Echo Client Connected. Starting UI t:{}. p:{}".format(transport, protocol))
	loop.run_forever()
	loop.close()
Esempio n. 32
0
        self.tranport = None
        self.deserializer = MobileCodePacket.Deserializer()

    def connection_mader(self, transport):
        self.tranport = transport
        packet = OpenSession()
        pakcet.Cookie = 100
        self.transport.write(packet.__serialize__())

    def data_received(self, data):
        self.deserializer.update(data)
        for pkt in deserializer.nextPackets():
            if isinstance(pkt, OpenSessionResponse):
                packet_back = RunMobileCode()
                packet_back.Cookie = 100
                with open("ParallelTSP_mobile") as file:
                    self.code = f.read()

                packet_back.Code = self.code
                self.tranport.write(packet_back.__serialize__())


loop = asyncio.get_event_loop()
loop.set_debug(enabled=True)
coro = playground.getConnector("plsmobile").create_playground_connection(fla5,\
                                                                   "20174.1.1337.6",1)

transport, protocol = loop.run_until_complete(coro)
loop.run_forever()
loop.close()
Esempio n. 33
0
        for pkt in self.deserializer.nextPackets():
            if isinstance(pkt, packetClass.RequestRecommandation):
                print("recommandation request received")
                message = packetClass.Question()
                message.ID = 1
                message.ask = "what is your skin type"
                packet1Bytes = message.__serialize__()
                self.transport.write(packet1Bytes)
                #self.serverstatus +=1
            elif isinstance(pkt, packetClass.Answer):
                print("Answer packet received")
                mes = self.facetype(pkt.answer)
                rs = packetClass.Result()
                rs.ID = 1
                rs.product = mes
                self.transport.write(rs.__serialize__())
            else:
                print("No data received from client")
                self.transport.close()

    # def sendRequest(self,request):
    #     self.transport.write(request.__serialize__())

if __name__ == "__main__":
    #server
    loop = asyncio.get_event_loop()
    coro = playground.getConnector().create_playground_server(EchoServerProtocol, 8888)
    server = loop.run_until_complete(coro)
    print("Echo Server Started at {}".format(server.sockets[0].gethostname()))
    loop.run_forever()
    loop.close()
Esempio n. 34
0
                OneAnswer = packetClass.Answer()
                OneAnswer.answer = "oliy"
                OneAnswer.ID = 1
                self.method(OneAnswer)
            elif isinstance(pkt, packetClass.Result):
                #self.clientstatus = 2
                print("Result packet received")
            else:
                print("finish")

    #method to get skintype
    def method(self,packet):
        self.transport.write(packet.__serialize__())

    def connection_lost(self, exc):
        print("connection lost")

if __name__ == "__main__":
    f = StackingProtocolFactory(lambda: PassThrough1(), lambda: PassThrough2())
    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    logging.getLogger().setLevel(logging.NOTSET)  # this logs *everything*
    logging.getLogger().addHandler(logging.StreamHandler())  # logs to stderr
    coro = playground.getConnector('passthrough').create_playground_connection(lambda:EchoClientProtocol(), '20174.1.1.1', 8888)
    server = loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()

Esempio n. 35
0
        
    def stdinAlert(self):
        data = sys.stdin.readline()
        if data and data[-1] == "\n":
            data = data[:-1] # strip off \n
        self.txProtocol.start_communication(data)



    
if __name__ == "__main__":

    logging.getLogger().setLevel(logging.NOTSET)
    logging.getLogger().addHandler(logging.StreamHandler())

    f = StackingProtocolFactory(lambda: PassthroughLayerOne(), lambda: PassthroughLayerTwo())
    ptConnector = playground.Connector(protocolStack=f)
    playground.setConnector("passthrough", ptConnector)
    
    loop = asyncio.get_event_loop()
    loop.set_debug(enabled=True)
    coro = playground.getConnector("passthrough").create_playground_server(lambda: MessagingServerProtocol(), 8000)
    server = loop.run_until_complete(coro)
    print("Server Started at {}\n".format(server.sockets[0].gethostname()))



    loop.run_forever()
    loop.close()

Esempio n. 36
0
from asyncio import Protocol
import asyncio
import playground
import sys
import logging
from Server import ClientControl, PassthroughLayerOne, PassthroughLayerTwo
from playground.network.common import StackingProtocol, StackingTransport, StackingProtocolFactory

    
if __name__ == "__main__":

	logging.getLogger().setLevel(logging.NOTSET)
	logging.getLogger().addHandler(logging.StreamHandler())

	f = StackingProtocolFactory(lambda: PassthroughLayerOne(), lambda: PassthroughLayerTwo())
	ptConnector = playground.Connector(protocolStack=f)
	playground.setConnector("passthrough", ptConnector)

	loop = asyncio.get_event_loop()
	loop.set_debug(enabled=True)

	control = ClientControl()
	coro = playground.getConnector("passthrough").create_playground_connection(control.buildProtocol, '20174.1.1.1', 8000)
	transport, protocol = loop.run_until_complete(coro)
	print("\n\nEcho Client Connected. Starting UI t:{}. p:{}".format(transport, protocol))
	loop.add_reader(sys.stdin, control.stdinAlert)
	control.connect(protocol)

	loop.run_forever()
	loop.close()