473,394 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

closing a "forever" Server Socket

Hi all,

This is my framework for create TCP server listening forever on a port
and supporting threads:
import SocketServer

port = 2222
ip = "192.168.0.4"
server_address = (ip, port)

class ThreadingTCPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer): pass

class Handler(SocketServer.BaseRequestHandler):
def handle(self):
# my handler

print "Listening for events at " + ip + ":" + str(port)
monitor_server = ThreadingTCPServer(server_address, Handler)

try:
monitor_server.serve_forever()
except KeyboardInterrupt:
monitor_server.socket.close()
print "Bye."
This server will not run as a daemon and for quitting you have to send
the SIGINT signal with Ctrl-C. It will rise the KeyboardInterrupt
exception, during its handling I simply close the socket and print a
message.

I want to ask if someone knows a better way for closing a "forever
server" or if there is a lack in my design.

Thank you!

Alessandro

Jan 18 '07 #1
6 16094
I want to ask if someone knows a better way for closing a "forever
server" or if there is a lack in my design.
Generally you don't create a 'forever server'. You create an 'until I
say stop' server. I would do this by looking at the 'serve_forever'
method, and implementing my own 'serve_until_?' method that is similar,
but will stop if a flag is set. Then you have to create a method for
setting that flag. It could be as simple as a keypress, or you could
add a quit method to your dispatcher that sets the flag when a certain
address is visited. That second method probably needs some added
security, otherwise anybody can just visit 'your.server.com/quit' and
shut it down.

Jan 18 '07 #2
thanks

infact the server_forever() method is only a serve() method inside an
infinite loop.

many thanks again,

Alessandro

Matimus ha scritto:
I want to ask if someone knows a better way for closing a "forever
server" or if there is a lack in my design.

Generally you don't create a 'forever server'. You create an 'until I
say stop' server. I would do this by looking at the 'serve_forever'
method, and implementing my own 'serve_until_?' method that is similar,
but will stop if a flag is set. Then you have to create a method for
setting that flag. It could be as simple as a keypress, or you could
add a quit method to your dispatcher that sets the flag when a certain
address is visited. That second method probably needs some added
security, otherwise anybody can just visit 'your.server.com/quit' and
shut it down.
Jan 22 '07 #3
alessandro írta:
thanks

infact the server_forever() method is only a serve() method inside an
infinite loop.

many thanks again,
Here is a snipped that show a "software terminateable threading TCP
socker server". The "server" object is a SocketServer instance,
server_stopped is a threading.Event instance. You should also import the
"select" module.

srvfd = server.fileno()
while not server_stopped.isSet():
ready = select.select([srvfd], [], [], 1) # Give one second
for incoming connection so we can stop the server in seconds
if srvfd in ready[0]:
server.handle_request()
else:
pass # log('No incoming connection, retrying')

Jan 22 '07 #4
Oh my God! it's really so complicated?

3 modules (threading, SocketServer, select) only for design a way to
shutdown a TCP server????
....but they told me that python was easy... :)

I'm working on a simulator and I have a monitor server that collects
information. I can shutdown it using Ctrl-C from the keyboard but for
my purpose could be very nice if I introduce a timer. So I could launch
my monitor like this:

../monitor 100

and my monitor will run for 100 seconds. For this I'm using the Timer
class provided by threading module, I have implemented a function like
this:

def shutdown():
sys.exit()

but it doesen't work because the server remain alive...maybe
SocketServer create immortal server...
I need only to close my application, there is a way to force the server
thread to close?

thanks!
Alessandro

Laszlo Nagy ha scritto:
alessandro írta:
thanks

infact the server_forever() method is only a serve() method inside an
infinite loop.

many thanks again,
Here is a snipped that show a "software terminateable threading TCP
socker server". The "server" object is a SocketServer instance,
server_stopped is a threading.Event instance. You should also import the
"select" module.

srvfd = server.fileno()
while not server_stopped.isSet():
ready = select.select([srvfd], [], [], 1) # Give one second
for incoming connection so we can stop the server in seconds
if srvfd in ready[0]:
server.handle_request()
else:
pass # log('No incoming connection, retrying')
Jan 22 '07 #5
alessandro írta:
Oh my God! it's really so complicated?

3 modules (threading, SocketServer, select) only for design a way to
shutdown a TCP server????
...but they told me that python was easy... :)
I believe that SockerServer was created for testing purposes, although
there are some programs using it in production. Yes, Python is easy. The
language is very clear, and you do not need to install third party
modules in order to create a server. :-) Of course the easiest way is to
call serve_forever. Isn't it easy? The other way is to implement your
own message handling loop. The SocketServer is flexible enough to do
this; and I don't think it is complicated. 7 lines of code will allow
you to stop the server safely from anywhere, even from other threads.
Try to implement the same in C or Delphi...
but it doesen't work because the server remain alive...maybe
SocketServer create immortal server...
I need only to close my application, there is a way to force the server
thread to close?
In pure Python, no. Python threads are "cooperative". In other words,
they cannot be terminated from outside. A thread will stop after the
execution exits its "run" method. (You can, of course terminate the
tread with an operating system function, but it is not recommended.)
Here is a class that can be stopped with an event:

import threading

stop_requested = threading.Event()

class SoftWaitThread(threading.Thread):
"""SoftWaitThread can wait for a given time except if the thread was
asked
to terminate itself."""
def waitsome(self,amount=10):
"""Wait the specified amount of time.

This can be terminated by stop_requested within 0.1 seconds."""
for idx in range(int(10*amount)):
time.sleep(0.1)
if stop_requested.isSet():
break
Then you can do this:

class MyServerThread(SoftWaitThread):
def run(self):
server = MySocketServerClass()
srvfd = server.fileno()
while not stop_requested.isSet():
ready = select.select([srvfd], [], [], 1)
if srvfd in ready[0]:

server.handle_request()
else:
pass
And then:

import time
def main():
sth = MyServerThread() # Create your thread
sth.start() # Start handling requests in another thread
try:
time.sleep(TIMEOUT_IN_SECONDS) # Wait...
finally:
stop_requested.set() # Request the server thread to stop itself
sth.join() # Wait until the server thread stops
print "Stopped."

You could start several threads and request them to stop with the same
event. I hope this helps.

Laszlo
p.s.: Not all of the above was tested, be careful.

Jan 22 '07 #6
At Monday 22/1/2007 14:49, alessandro wrote:
>Oh my God! it's really so complicated?

3 modules (threading, SocketServer, select) only for design a way to
shutdown a TCP server????
...but they told me that python was easy... :)
You already have the answer: replace serve_forever with your own loop.
>I'm working on a simulator and I have a monitor server that collects
information. I can shutdown it using Ctrl-C from the keyboard but for
my purpose could be very nice if I introduce a timer. So I could launch
my monitor like this:
./monitor 100

and my monitor will run for 100 seconds. For this I'm using the Timer
This is simple enough, I presume:

try:
stopt = time.time()+100
while time.time()<stopt:
server.handle_request()
except KeyboardInterrupt: pass
# shutdown

The drawback is that it won't leave the loop until a request arrives,
but this may not be a problem for you. (Other suggestions are more
complicated because of this issue.)
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 22 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Yannick Turgeon | last post by:
Hello all, I'm using SS 2000 and NT4 (and Access97 as front-end on another server) Well, probably by lack of knowledge about table locks, I don't really know where to start to present this...
10
by: mike | last post by:
regards: I use Jtidy (api) to translate a HTML file into a "XHTML file". But The "XHTML file" cannot be identified by nokia 6600. Do I miss something important? Or this is Jtidy's weakness or...
0
by: Johann Blake | last post by:
I am using the TcpClient to connect to a web site. I then open a NetworkStream and read the contents that are being sent back. The problem is that I have no idea when the remote host is finished...
21
by: Neel | last post by:
I am trying to "ping" a remote host in my C++/Redhat Linux code to check whether that host is connected or not. if (0 == system("ping -w 2 192.168.0.2)) But, in both cases...
11
by: Tor Erik | last post by:
Hi, The reason is that my application does about 16 connects and data transfers per second, to the same 16 remote hosts. After approx 200 secs there are 4000 sockets waiting to be garbage...
1
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting"...
4
by: dumbkiwi | last post by:
I have written a script that uses the urllib2 module to download web pages for parsing. If there is no network interface, urllib2 hangs for a very long time before it raises an exception. I...
11
by: atlaste | last post by:
Hi, In an attempt to create a full-blown webcrawler I've found myself writing a wrapper around the Socket class in an attempt to make it completely async, supporting timeouts and some scheduling...
1
by: danfolkes | last post by:
Hey Everyone, I am trying to send repeated messages from a "Node" to a "Server". It works the first time I send the from the Node to Server, but after that it either errors, or does not do...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.