<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">from threading import Thread
import socket
import string

class ServeClient(Thread):

    def __init__(self,socket,con_id):
        Thread.__init__(self)
        self.socket = socket
        self.con_id = con_id
        #The state variable keeps track of the state of the application
        #protocol. The user should give the expected reply at the expected
        #points. For example, s/he cannot reply "Addition: ..." at the prompt
        #"Hi! What is your name?".
        self.state = 0

    def run(self):
        msg = ''

        while msg != 'Quit\n':
            #main loop of handling messages
            msg = self.socket.recv(512)
            if ((self.state == 0) &amp; (msg == 'Hello!\n')):
                # Implement me :)  
            elif ((self.state == 1) &amp; (string.find(msg,'My name is') != -1)):
                # Implement me :)
            elif ((self.state == 2) &amp; (string.find(msg,'Addition:') != -1)):
                # Implement me :)
            elif msg == 'Quit\n':
                self.socket.send('Buy!')
            else:
                self.socket.send('Wrong reply! Try again.')

        print 'Connection ' + str(self.con_id) + ' closed!'
        self.socket.close()



print 'Hi! I am the addition server!'
#Create a socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Give a port number to the socket (22000).
#The ip address 127.0.0.1 is a different name to identify 
#the computer that we are working on (local host).
#This means that only processes that are executed in this computer
#can access the socket we create.
serversocket.bind(('127.0.0.1', 22000))
#Wait until somebody wants to connect with the socket.
serversocket.listen(5)

connection_counter = 0
while 1:
    #Accept connections from outside
    (clientsocket, address) = serversocket.accept()
    #A new socke is created, the clientsocket, dedicated to the
    #specific connection
    connection_counter += 1
    print 'Connection ' + str(connection_counter) + ' accepted!'
    #Spawn a thread to serve the connection
    client_thread = ServeClient(clientsocket, connection_counter)
    client_thread.start()


# vim:expandtab:tabstop=8:shiftwidth=4:softtabstop=4

</pre></body></html>