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.
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))
|
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:
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:
to test, run server in one terminal, and from another terminal do: