Thursday, August 18, 2016

Python socket server with handling multiple client connections

In this post describes how to write socket server with handling multiple client connections in python.

Creation of socket server needs following steps:
  • bind socket to port
  • start listening
  • wait for client
  • receive and send data
Sample Code for Socket Server

import socket
import sys
from thread import *
import logging

host = ''
port = 8001

logging.basicConfig(level=logging.DEBUG)

#initiate socket creating
logging.info('# creating socket')
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
logging.debug('# created socket : ' + str(s))

try:
    s.bind((host, port))
except socket.error as message:
    logging.error('# socket binding failed : ' + str(message))
    sys.exit()

logging.info('# socket binding success')

#start listning on socket
s.listen(5)
logging.info('# socket listning')

#handler for client threads
def client_thread_handler(conn):
    #sending msgs to connected clients
    conn.send('hi... u r now connected')

    #loop for not terminate or end thread
    while True:
        data = conn.recv(1024)
        print(data)

        if str(data) == 'exit':
            logging.info('# exiting from thread')
            break

        reply = 'reply... ' + data
        conn.sendall(reply)

    conn.close()


#waiting for data from client
while True:
    conn, addr = s.accept()
    logging.info('# connected to : ' + str(addr))
    start_new_thread(client_thread_handler, (conn,))

s.close()

After running the server will run on the localhost port 8001.
To test this you can create a socket client or telnet to port 8001.

Testing with telnet type following in shell:

telnet localhost 8001