SocketServer - Interrupting get_request()
Neil Edwards
neil at anyisle.org
Thu Feb 7 19:08:06 EST 2002
Hi there, I am currently writing a piece of code based on
some code I saw here (in the group). Basically I am
trying to write a simple MUD in python using the SocketServer
class and am having trouble when it comes to shutting down
the server from a client.
Here is the code so far:
#! /usr/bin/python -O
import sys, SocketServer, socket
import string
true = 1
false = 0
PORT = 2001
serverUp = false
connections = [] #list of all client sockets
class RequestServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = 1
class RequestHandler(SocketServer.StreamRequestHandler):
def handle(self):
global serverUp, connections
host, port = self.client_address
print "Connected by", host, port
connections.append(self.connection)
# get data
while true:
request = self.rfile.readline()
self.server.request = request
request = string.rstrip(request)
print request
if(request == "shutdown"):
for eachConnection in connections:
eachConnection.send("Shutting down NOW!\n")
serverUp = false
#FIXME - Need someway of stopping server tasks
def main():
global serverUp
# get port
if len(sys.argv) > 1:
port = int(eval(sys.argv[1]))
else:
port = PORT
print "Waiting..."
server = RequestServer(('', port), RequestHandler)
serverUp = true
while(serverUp):
server.handle_request() # do not server forever - serve just 1 request
print "Closing all connections..."
for eachConnection in connections:
eachConnection.close()
main()
Wondered if anyone had any ideas, basically the server seems to block
waiting
for the next connection and so I can't end the program while it is blocked
(I even tried a sys.exit(0) where the FIXME is and it didn't exit)
Sorry if my code looks a bit poor this is one of the first progs I've done
in python)
Full credit to the original author of the code by the way!!
Thanks for making it public!
Thanks for the help
---
Neil Edwards (neil at anyisle.org)
http://anyisle.org
More information about the Python-list
mailing list