#!/usr/bin/env python # this script runs a TCP socket and listens for an input string # as soon as it receives it, the string is used to generate a # reply from megahal, which is then sent back to the socket # # CTRL+C is trapped and triggers: # * TCP socket closure # * megahal state staving # * server exit import mh_python import signal import socket import string import sys import time host = '' port = 8112 backlog = 2 size = 1024 def signal_handler(signal, frame): print 'You pressed Ctrl+C!' mh_python.cleanup() #client.close() s.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) def generate_reply(sentence): "Return a string containing a reply to input sentence." reply = mh_python.doreply(sentence) time.sleep(4) return reply s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) mh_python.initbrain() while 1: client, address = s.accept() sentence = client.recv(size) if sentence: sentence=string.strip(sentence) print 'Lui:', sentence reply = generate_reply(sentence) print 'Io:', reply client.send(reply) client.close()