One more socket programming question

John Salerno johnjsal at gmailNOSPAM.com
Wed Jun 18 04:47:07 CEST 2008


I'm now experimenting with the SocketServer class. Originally I 
subclassed the StreamRequestHandler to make my own custom handler, but a 
result of this seems to be that the client socket closes after it has 
been used, instead of staying open.

Just as a test, I decided to use BaseRequestHandler instead, because I 
know its methods aren't implemented. So this is what I have:

-----
import SocketServer

host = ''
port = 51234
address = (host, port)
buffer_size = 1024

class MyRequestHandler(SocketServer.BaseRequestHandler):
     def handle(self):
         print '...connected from:', self.client_address
         data = self.request.recv(buffer_size)
         self.request.send('%s %s' % ('You typed:', data))

socket_server = SocketServer.TCPServer(address, MyRequestHandler)
print 'waiting for connection...'
socket_server.serve_forever()
------

------
from socket import *

host = 'localhost'
port = 51234
address = (host, port)
buffer_size = 1024

client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(address)

while True:
     data = raw_input('> ')
     if not data:
         break
     client_socket.send(data)
     data = client_socket.recv(buffer_size)
     print data

client_socket.close()
------

But this only seems to work one time, and then subsequent attempts 
return nothing, and then the client program seems to crash (or just 
close on its own).

What's happening here?



More information about the Python-list mailing list