Socket Programming: Handling multiclients

Referring to previous post, we will continue with same code. In this post we will try to handle multiple clients. You can read rest of the post on my personal website, here is the link.

Multiple clients means that multiple client programs can connect to server program. For this we will use threads. Threads are nothing but process and runs only the part that is required (we decide what is going to run) to be run.

There will be a minor change in both server and client programs.

Required: Python 2.6+

Using:

server.py

#!/usr/bin/python

# Import all from module socket
from socket import *
#Importing all from thread
from thread import *

# Defining server address and port
host = ''  #'localhost' or '127.0.0.1' or '' are all same
port = 52000 #Use port > 1024, below it all are reserved

#Creating socket object
sock = socket()
#Binding socket to a address. bind() takes tuple of host and port.
sock.bind((host, port))
#Listening at the address
sock.listen(5) #5 denotes the number of clients can queue

def clientthread(conn):
#infinite loop so that function do not terminate and thread do not end.
     while True:
#Sending message to connected client
         conn.send('Hi! I am server\n') #send only takes string
#Receiving from client
         data = conn.recv(1024) # 1024 stands for bytes of data to be received
         print data

while True:
#Accepting incoming connections
    conn, addr = sock.accept()
#Creating new thread. Calling clientthread function for this function and passing conn as argument.
    start_new_thread(clientthread,(conn,)) #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.

conn.close()
sock.close()

Use the same client.py code for client from previous post.

#!usr/bin/python
from socket import *

host = 'localhost' # '127.0.0.1' can also be used
port = 52000

sock = socket()
#Connecting to socket
sock.connect((host, port)) #Connect takes tuple of host and port

#Infinite loop to keep client running.
while True:
    data = sock.recv(1024)
    print data
    sock.send('HI! I am client.')

sock.close()

Understanding :

Highlighted code is the changes done in the previous code we had.

What we have done in server.py is we took the communicating part inside the infinite while loop of function clientthread and using it in thread on line 32.

In client.py we took the communicating part inside the infinite while loop.

Everything else is explained in comments.

Note:

  • Programs will not terminate by themselves because they will never come out of loop. So certainly you will receive error that socket is already in use.
  • start_new_thread() takes 3 arguments. 3rd argument is kwargs which is of no use right now.
  • 2nd argument of start_new_thread has to be a tuple. Tuples are fixed length array in python.
  • Module threading can also be used for threading.
  • start_new() is identical to start_new_thread().
  • 5 in sock.listen(5) in server.py is of no use as every client will interact with server. May be it  will be required when server can not handle more process.

My personal website is up and all new blog posts will only be available on https://neerajkhandelwal.com.

Advertisements

9 thoughts on “Socket Programming: Handling multiclients

    1. Hey, it can but it will be highly complex as well as reinventing the wheel unless you are writing your own protocol. Otherwise, I recommend checking out Node.js and it’s environment which is being used to solve problems like these industry wide.

  1. Beautiful, thank you. Got started with sockets using the multiprocessor Listener and it doesn’t seem to support multiple clients, so I got confused about whether that was easily supported with sockets, and this answered the question perfectly and cleanly.

      1. Definitely! And it made me realize what I was doing wrong with the multiprocessor Listener code as well. In order to connect to multiple clients all I need to do is loop back to the accept() function in the main thread.

        Very nice and simple, this is by far the clearest and most helpful example of this socket server multi-client host design pattern. Thanks again 🙂

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