Signup/Sign In

Handling Received Client Data over TCP Socket

Now we will have an example in which the client sends some data to the server and the server handles the data as instructed. We'll see two different usecases for this:

  • Echo Client-Server Program
  • Handling received data by adding them

Simple Client-Server Program

In this program the server simply echos the data that is received from the client. You must have seen some web portals which echo(prints) back your details as soon as you visit their page. First, we create the server. We start by creating a TCP socket object. We bind the socket to the given port on our local machine. In the listening stage, we make sure we listen to multiple clients in a queue using the backlog argument to the listen() method. Finally, we wait for the client to get connected and send some data to the server. When the data is received, the server echoes back the data to the client.

echo_server.py

#!usr/bin/python

import socket
host = socket.gethostname()
port = 12345
s = socket.socket()		# TCP socket object
s.bind((host,port))
s.listen(5)

print "Waiting for client..."
conn,addr = s.accept()	        # Accept connection when client connects
print "Connected by ", addr

while True:
	data = conn.recv(1024)	    # Receive client data
	if not data: break	        # exit from loop if no data
	conn.sendall(data)	        # Send the received data back to client
conn.close()

Above code executes as:

 Server Program waiting for client connection


echo_client.py

#!usr/bin/python

import socket
host = socket.gethostname()
port = 12345
s = socket.socket()		# TCP socket object

s.connect((host,port))

s.sendall('This will be sent to server')    # Send This message to server

data = s.recv(1024)	    # Now, receive the echoed
					    # data from server

print data				# Print received(echoed) data
s.close()				# close the connection

Now, as the server is already up and running, we should run our echo_client.py

Echo Server Program


Performing Operation on Data in Client-Server Program

In this program we will send information to the server and the server will sum up the data and will send back to the client. But, What's new in this?

Well, you'll see that when we are sending 2 numbers to server for addition we are not sending it as two integers rather we will be sending the data as a string. Say, we want to add 4 and 5 so we will send 4 and 5 as a string '4,5'. Notice the comma , in between 4 and 5. This acts as a separator for the two integers.

On the server, as we receive the string '4,5', we will extract the integers from the string, add them and then send the result back to the client by converting the addition result into a string.

add_server.py

#!usr/bin/python

import socket
host = socket.gethostname()
port = 12345
s = socket.socket()		    # TCP socket object
s.bind((host,port))

s.listen(5)

conn, addr = s.accept()
print "Connected by ", addr
while True:
	data=conn.recv(1024)
	# Split the received string using ','
	# as separator and store in list 'd'
	d = data.split(",")	    
	
	# add the content after converting to 'int'
	data_add = int(d[0]) +int(d[1]) 
	
	conn.sendall(str(data_add))	    # Send added data as string
					                # String conversion is MUST!
conn.close()

add_client.py

#!usr/bin/python

import socket

host = socket.gethostname()
port = 12345

a = str(raw_input('Enter first number: '))	# Enter the numbers
b = str(raw_input('Enter second number: '))	# to be added
c = a+','+b					# Generate a string from numbers

print "Sending string {0} to server" .format(c)

s = socket.socket()
s.connect((host,port))

s.sendall(c)				# Send string 'c' to server
data = s.recv(1024)			# receive server response
print int(data)				# convert received dat to 'int'

s.close()					#Close the Connection

Now, run add_server.py first and after that run add_client.py


Output:

Echo Server Program