Created
May 1, 2019 08:25
-
-
Save cjjavellana/1024c87cf3ae4d15fdd27f1ceafc0c75 to your computer and use it in GitHub Desktop.
A Simple Telnet Chat App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import _thread | |
import threading | |
import queue | |
import socket | |
import signal | |
import sys | |
class ClientInputReader(threading.Thread): | |
def __init__(self, conn, addr): | |
threading.Thread.__init__(self) | |
self.conn = conn | |
self.addr = addr | |
def run(self): | |
while True: | |
msg = self.conn.recv(4096) | |
msg_as_string = msg.decode('utf-8') | |
print(self.addr, '>>', msg_as_string) | |
if(msg_as_string == 'quit()'): | |
break | |
class ClientOutputWriter(threading.Thread): | |
def __init__(self, conn, addr, queue): | |
threading.Thread.__init__(self) | |
self.conn = conn | |
self.addr = addr | |
self.queue = queue | |
def run(self): | |
while True: | |
msg = self.queue.get() | |
print('Sending {} to {}'.format(msg, self.conn)) | |
self.conn.send(str.encode(msg)) | |
class StdinReader(threading.Thread): | |
def __init__(self, queue): | |
threading.Thread.__init__(self) | |
self.queue = queue | |
def run(self): | |
while True: | |
msg = input(" >> ") | |
if msg == 'quit()': | |
break | |
self.queue.put(msg) | |
class Server(threading.Thread): | |
def __init__(self, host='127.0.0.1', port=8194, queue = None): | |
threading.Thread.__init__(self) | |
self.host = host | |
self.port = port | |
self.queue = queue | |
def run(self): | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
s.bind((self.host, self.port)) | |
s.listen(5) | |
conn, addr = s.accept() | |
client_thread = ClientInputReader(conn, addr) | |
client_thread.start() | |
output_thread = ClientOutputWriter(conn, addr, self.queue) | |
output_thread.start() | |
def signal_handler(sig, frame): | |
print('You pressed Ctrl+C!') | |
sys.exit(0) | |
def main(): | |
q = queue.Queue() | |
std_thread = StdinReader(q) | |
std_thread.start() | |
server_thread = Server(queue=q) | |
server_thread.start() | |
signal.signal(signal.SIGINT, signal_handler) | |
signal.pause() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment