100% CPU Usage when a tcp client is disconnected

T

Tzury Bar Yochay

The following is a code I am using for a simple tcp echo server.
When I run it and then connect to it (with Telnet for example) if I
shout down the telnet the CPU tops 100% of usage and saty there
forever.
Can one tell what am I doing wrong?

#code.py

import SocketServer

class MyServer(SocketServer.BaseRequestHandler ):
def setup(self):
print self.client_address, 'connected!'
self.request.send('hi ' + str(self.client_address) + '\n')

def handle(self):
while 1:
data = self.request.recv(1024)
self.request.send(data)
if data.strip() == 'bye':
return

def finish(self):
print self.client_address, 'disconnected!'
self.request.send('bye ' + str(self.client_address) + '\n')

#server host is a tuple ('host', port)
server = SocketServer.ThreadingTCPServer(('', 50008), MyServer)
server.serve_forever()
 
A

Aaron Watters

The following is a code I am using for a simple tcp echo server.
When I run it and then connect to it (with Telnet for example) if I
shout down the telnet the CPU tops 100% of usage and saty there
forever....
def handle(self):
while 1:
data = self.request.recv(1024)
self.request.send(data)
if data.strip() == 'bye':
return

I forget exactly how the superclass works, but
that while 1 looks suspicious. Try chaning it
to

data = "dummy"
while data:
...

-- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=help+infinite+loop
 
H

Hrvoje Niksic

Tzury Bar Yochay said:
The following is a code I am using for a simple tcp echo server.
When I run it and then connect to it (with Telnet for example) if I
shout down the telnet the CPU tops 100% of usage and saty there
forever. Can one tell what am I doing wrong?

If you shut down telnet, self.request.recv(1024) returns an empty
string, meaning EOF, and you start inflooping.
 
S

Scott David Daniels

Aaron said:
... Try changing it to ...
data = "dummy"
while data:
...

Even better:
from functools import partial

def handle(self):
for data in iter(partial(self.request.recv, 1024), ''):
self.request.send(data)
if data.strip() == 'bye':
break
else:
raise ValueError('Gone w/o a "bye"') # or IOError

-Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top