import socket, threading s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 1911)) s.listen(1) lock = threading.Lock() welcome_message = 'Welcome to MUD\n1. Go west\n2. Open a window\n3. Quit\n' def play_sound(): #sound the horn return def open_window(): # open a window return class daemon(threading.Thread): def __init__(self, (socket,address)): threading.Thread.__init__(self) self.socket = socket self.address = address def run(self): # display welcome message self.socket.send(welcome_message) while(True): # wait for keypress + enter data = self.socket.recv(1024) # handle menu alterantives and set proper return message if data[0] == '1': play_sound() data = 'The place looks the same as before\n' # execute some function elif data[0] == '2': open_window() data = 'I feel a chilly wind\n' # execute some other function elif data[0] == '3': break; else: data = welcome_message # send the designated message back to the client self.socket.send(data); # close connection self.socket.close() while True: daemon(s.accept()).start()
Now connecting with
telnet localhost 1911
will give us the following output:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Welcome to MUD 1. Go west 2. Open a window 3. Quit