Exemplo n.º 1
0
class CommandLineChatClient:
    PROMPT = '> '

    def __init__(self, username, desthost, destport):
        self.username = username
        self.desthost = desthost
        self.destport = destport

    # TODO: The func name "run" seems to imply async call in this
    # application. Change all occurrences of "run" with something else
    # for cases when it's a blocking call?
    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.desthost, self.destport))
        sockhandlers = (self.peer_connected, self.peer_msg_received, self.peer_disconnected)
        self.sockio = TCPSocketIOWorker(sock, sockhandlers, msgsize=MESSAGE_SIZE)
        self.sockio_thread = Thread(target=self.sockio.run)
        self.sockio_thread.start()
        while True:
            try:
                msg = input(self.PROMPT)
                msg = '<{}> {}'.format(self.username, msg)
                self.sockio.sendmsg(msg)
            except KeyboardInterrupt:
                self._teardown()
                break

    def peer_connected(self, sockio):
        print('Connected to server ({})'.format(sockio))

    def peer_msg_received(self, sockio, msg):
        msg = msg.rstrip()

        sys.stdout.write('\r{}\n'.format(msg))
        # TODO: Not sure why I have to \r this one again.
        sys.stdout.write('\r{}'.format(self.PROMPT))

    def peer_disconnected(self, sockio):
        sys.stdout.write('CHAT SERVER CLOSED THE CONNECTION!\n')

    def _teardown(self):
        print('Tearing down connection')
        self.sockio.shutdown()
        self.sockio_thread.join()
Exemplo n.º 2
0
 def run(self):
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.connect((self.desthost, self.destport))
     sockhandlers = (self.peer_connected, self.peer_msg_received, self.peer_disconnected)
     self.sockio = TCPSocketIOWorker(sock, sockhandlers, msgsize=MESSAGE_SIZE)
     self.sockio_thread = Thread(target=self.sockio.run)
     self.sockio_thread.start()
     while True:
         try:
             msg = input(self.PROMPT)
             msg = '<{}> {}'.format(self.username, msg)
             self.sockio.sendmsg(msg)
         except KeyboardInterrupt:
             self._teardown()
             break