A very simple telnet server example

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s