a simple but userful multithreaded TCP server in Python

I wrote this piece of code for binding a TCP port and listen for any incoming request and dump them on the stdout.  

Two usages has been proved useful so far:

1. to simulate a "server not responsing", TCP connect established but suck in all request.

2. to debug a nasty HTML generated from a jsp, and find out exactly what has been send to the server. It needs to save the problematic HTML on local hard driver, change its form action to the listening host and port, then bang.. you will see the HTTP headers.  

============================

#!/usr/bin/env python

import socket
import threading

# msg
msg=’HTTP/1.1 200 OKn’
msg+=’Content-type:text/plainn’

def doCool(socket,address):
    print ‘*****************************’
    data=socket.recv(1024)
    print data
    print ‘*****************************’

    #socket.send(msg)
    #socket.close()
   

address_family = socket.AF_INET

socket_type = socket.SOCK_STREAM

request_queue_size=5

serversocket=socket.socket(address_family,socket_type)
serversocket.bind((socket.gethostname(), 80))
#serversocket.bind((socket.gethostname(), 10000))
print socket.gethostname()
serversocket.listen(request_queue_size)

 

 

while 1:
    #accept connections from outside
    (clientsocket, address) = serversocket.accept()

    t = threading.Thread(target = doCool,
                         args = (clientsocket, address))
    t.start()

 

serversocket.close()

Advertisements
This entry was posted in TCP. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s