Welcome, guest | Sign In | My Account | Store | Cart

TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer. Sometimes you need a quick deployment of a TCP server and here I bring to you a Python 2.* snippet of a threaded Python server.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from socket import *
import thread
 
BUFF = 1024
HOST = '127.0.0.1'# must be input parameter @TODO
PORT = 9999 # must be input parameter @TODO

def gen_response():
    return 'this_is_the_return_from_the_server'
 
def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFF)
        print 'data:' + repr(data)
        if not data: break
        clientsock.send(gen_response())
        print 'sent:' + repr(gen_response())
        clientsock.close()
 
if __name__=='__main__':
    ADDR = (HOST, PORT)
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock.bind(ADDR)
    serversock.listen(5)
    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from:', addr
        thread.start_new_thread(handler, (clientsock, addr))

2 comments

Lj 11 years, 7 months ago  # | flag

this code did not work for me as it was reporting errors.... after toying around and figuring out harder errors this is final code that worked for me. If I have missed authors idea, please correct.... here it is:

from socket import *
import thread

BUFF = 1024
HOST = '127.0.0.1'# must be input parameter @TODO
PORT = 9999 # must be input parameter @TODO
def response(key):
    return 'this_is_the_return_from_the_server'

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFF)
        print 'data:' + repr(data)
        if not data: break
        clientsock.send(response(''))
        print 'sent:' + repr(response(''))
        # clientsock.close() # - reports [Errno 9] Bad file descriptor as it looks like that socket is trying to send data when it is already closed

if __name__=='__main__':
    ADDR = (HOST, PORT)
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock.bind(ADDR)
    serversock.listen(5)
    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from:', addr
        thread.start_new_thread(handler, (clientsock, addr))
Lj 11 years, 7 months ago  # | flag

Realized later that clientsock.close() may have wrong indent, it shall be aligned with while. In this way if connection is broken from a client side, server will close its socket too, added better logging.

a bit more elaborated example:

from socket import *
import thread

BUFF = 1024
HOST = '127.0.0.1'# must be input parameter @TODO
PORT = 9999 # must be input parameter @TODO
def response(key):
    return 'Server response: ' + key

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFF)
        if not data: break
        print repr(addr) + ' recv:' + repr(data)
        clientsock.send(response(data))
        print repr(addr) + ' sent:' + repr(response(data))
        if "close" == data.rstrip(): break # type 'close' on client console to close connection from the server side

    clientsock.close()
    print addr, "- closed connection" #log on console

if __name__=='__main__':
    ADDR = (HOST, PORT)
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock.bind(ADDR)
    serversock.listen(5)
    while 1:
        print 'waiting for connection... listening on port', PORT
        clientsock, addr = serversock.accept()
        print '...connected from:', addr
        thread.start_new_thread(handler, (clientsock, addr))

to test, run server in one terminal, and from another terminal do:

telnet localhost 9999
Created by Luis Martin Gil on Fri, 24 Aug 2012 (MIT)
Python recipes (4591)
Luis Martin Gil's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks