Exemple #1
0
 def send(self, text, *args):
     # The args is mostly for relaying a message to a recipient and showing the sender's name
     # Otherwise, it just prompts the client that it was a server message
     if args:
         self.transport.write("{0:s} [{1:s}]: {2:s}\n".format(tstamp(),*args, text).encode())
     else:
         self.transport.write("{0:s} [SERVER]: {1:s}\n".format(tstamp(),text).encode())
Exemple #2
0
 def send(self, text, *args):
     if args:
         self.transport.write("{0:s} [{1:s}]: {2:s}\n".format(
             tstamp(), *args, text).encode())
     else:
         self.transport.write("{0:s} [SERVER]: {1:s}\n".format(
             tstamp(), text).encode())
Exemple #3
0
    def handle_request(self,request):
        print(data)
        if request.action is 'Add':
            self.send("Echo: Add")
            self.send(request)
            pass

        if request.action is 'Update':
            self.send("Echo: Update")
            self.send(request)
            pass

        if request.action is 'Delete':
            self.send("Echo: Delete")
            self.send(request)
            pass

        if request.action is 'Block':
            self.send("Echo: Block")
            self.send(request)
            pass

        if request.action == "contacts":
            contacts= self.db.query_contact(self.username)
            print("{0:s} [SERVER]: contacts for: {1:}".format(tstamp(),self.username))
            print(*tuple(contacts[i] for i in range(len(contacts))), sep="\n")


            # Get all the contacts, and send them over the socket one at a time
            # This can be done another way in bulk, but it is easier to send them one and display it in terminal
            # on the client side, instead of having the client responsible for formatting the display.
            for c in contacts:
                self.send("{}".format(c))
Exemple #4
0
 def connection_made(self, transport):
     self.transport = transport
     peername = transport.get_extra_info("peername")
     self.username = ""
     self.addr = "{:s}:{:d}".format(*peername)
     print("{0:s}: {1:s} connected".format(tstamp(), self.addr))
     self.send("connected")
     clients.append(self)
Exemple #5
0
    def connection_lost(self, ex):
        print("{0:s} connection lost: {1:s}".format(tstamp(), self.username))
        clients.remove(self)
        del cList[self.username]

        # Fix this
        for client in clients:
            client.send("{:s} disconnected".format(self.username))
Exemple #6
0
    def connection_lost(self, ex):
        print("{0:s} connection lost: {1:s}".format(tstamp(),self.username) )
        clients.remove(self)
        # del cList[self.username]
        del clientSession[self.username]

        # Fix this, only broadcast a user disconnected to someone chatting
        # Right now, message is sent to all clients connected.
        for client in clients:  #FIXME
            client.send("{:s} disconnected".format(self.username))
Exemple #7
0
    def handle_request(self, data):
        print(data)
        if data.req == "contacts":
            contacts = self.db.query_contact(self.username)
            print("{0:s} [SERVER]: contacts for: {1:}".format(
                tstamp(), self.username))
            print(*tuple(contacts[i] for i in range(len(contacts))), sep="\n")

            for c in contacts:
                self.send("{}".format(c))
Exemple #8
0
    def data_received(self, data):
        data = loads(data)
        print(tstamp() + " received: {}\n".format(data))
        if len(data) == 0:
            return

        if type(data) == Login:
            self.handle_login(data)

        if type(data) == Sender:
            self.handle_message(data)

        if type(data) == Request:
            self.handle_request(data)
Exemple #9
0
async def client_talk(loop):
    usr = await prompt_async("username:"******"password:"******">"
    contacts = []
    history = InMemoryHistory()
    cli = CommandLineInterface(application=create_prompt_application(
        cin,
        history=history,
        completer=cmd_complete,
        get_bottom_toolbar_tokens=toolbar_tokens),
                               eventloop=loop)

    sys.stdout = cli.stdout_proxy()
    client[0].send(Login(usr, pwd))
    cin = usr + ">"

    while True:
        try:
            msg = await cli.run_async()
            msg = msg.text
            try:
                if msg.startswith("/"):
                    msg = msg.split(sep="/")
                    if msg[1] == "bye":
                        client[0].close_conn()

                    elif msg[1] == "contacts":
                        client[0].send(Request("contacts", usr))

                    elif msg[1] == "send":
                        client[0].send(Message(msg[2], msg[3]))
                        print("{0:s} [{1:s}]: {2:s}\n".format(
                            tstamp(), usr, msg[3]))
                    else:
                        raise IndexError
            except IndexError:
                print("Not understood.")
                continue

        except (EOFError, KeyboardInterrupt):
            return
Exemple #10
0
    def data_received(self, data):
        data = loads(data)                                          # Unpack that binary data
        print(tstamp() + ' [{}]:'.format(self.username),end='')     # print the data source
        print(" {}\n".format(data))                                 # print the data

        if len(data) == 0:                  # If the size of data is 0, there's nothing, so return
            return

        elif type(data) == Login:             # if data is a Login tuple, send to handler
            self.handle_login(data)

        elif type(data) == Request:           # If data is a Request tuple, send to handler
            self.handle_request(data)

        elif type(data) == Message:           # if data is a Message tuple, send to handler
            self.handle_message(data)

        else:                                 # If message type is not recognized, idk what to do.
            print('Unknown data type, ignoring.')
            return
Exemple #11
0
        if request.action == "contacts":
            contacts= self.db.query_contact(self.username)
            print("{0:s} [SERVER]: contacts for: {1:}".format(tstamp(),self.username))
            print(*tuple(contacts[i] for i in range(len(contacts))), sep="\n")


            # Get all the contacts, and send them over the socket one at a time
            # This can be done another way in bulk, but it is easier to send them one and display it in terminal
            # on the client side, instead of having the client responsible for formatting the display.
            for c in contacts:
                self.send("{}".format(c))
        
# ===============================================================================

if __name__ == '__main__':
    print("{0:s} [SERVER]: starting.".format(tstamp()))

    loop = asyncio.get_event_loop()

    # Creates the asychronous server, is a generic base class of asynchio
    coroutine = loop.create_server(Server, 'localhost', 9999)
    
    server = loop.run_until_complete(coroutine)

    # If this is kinda confusing look up what "futures" are in python
    # This creates a "future" coroutine for the console. It hasn't been created yet though.
    asyncio.ensure_future(server_console(create_asyncio_eventloop(loop)))

    for socket in server.sockets:
        # Just printing the address and port that it is running on.
        print("{0:s} [SERVER]: running on {1:}".format(tstamp(), socket.getsockname()))
Exemple #12
0
        cList[data.username] = self

    def handle_request(self, data):
        print(data)
        if data.req == "contacts":
            contacts = self.db.query_contact(self.username)
            print("{0:s} [SERVER]: contacts for: {1:}".format(
                tstamp(), self.username))
            print(*tuple(contacts[i] for i in range(len(contacts))), sep="\n")

            for c in contacts:
                self.send("{}".format(c))


# ===============================================================================

if __name__ == '__main__':
    print("{0:s} [SERVER]: starting.".format(tstamp()))
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(Server, '127.0.0.1', 9999)

    server = loop.run_until_complete(coroutine)
    asyncio. async (server_console(create_asyncio_eventloop(loop)))
    for socket in server.sockets:
        print("{0:s} [SERVER]: running on {1:}".format(tstamp(),
                                                       socket.getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass