Socket Programming in Python
Introduction
In my last article at Evolt, I had discussed socket programming in Perl. In this article, I shall discuss socket
programming in Python. You need not know anything about Perl or socket programming in Perl, nonetheless you
might want to refer it if you wish to.
Sockets are one of the most popular means of network communication. It follows the client-server architecture that
most of you-all must be aware of. Using sockets in Python, it is possible to communicate to a server using a client
program. Here, I will explain how using sockets a client program can communicate to a server. The client program
is run at the client-side while the server program runs in the Internet. For testing the program, you can run it on a
local server.
For socket programming, Python provides the socket module. It is a very common module and it's most likely
that you have it. The socket module consists of the socket() function, which is used for socket
initiation/creation. We will be primarily concerned with this function only, i.e. socket.socket(). The socket
module also provides several other methods.
The socket module supports various protocols for communication, viz., TCP (Transmission Control Protocol), UDP
(User Datagram Protocol), etc. TCP is a connection-oriented protocol, which means before a client can send
messages with the server, a connection needs to be explicitly created to the server, and only then can the client-
server communication take place. On the other hand, UDP is a connectionless protocol, which means no connection
needs to be established between the client and the server for communication. Since, protocols are not the main
concern of this article, I won't elucidate on them any further. Since we are concerned with socket programming (in
Python), it would be better to make use of a simple protocol; thus in the Python examples that follow, I have used
the connectionless UDP protocol.
Before we go further with our UDP client and servers, this is how you must import the socket module:
from socket import *
Client Program
First of all we need to initialize all the parameters that we will be using to initialize our socket:
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
The various variables we have created have the following meaning for the socket:
<b>host</b>: The host can be a host name or an IP address.
Here we are testing the programs locally so we have used
localhost. If the server program is running in the Internet
then you must use its IP address or domain name.
<b>port</b>: The port can be a number or symbolic service
name.
<b>buf</b>: buf is the maximum size of the data stream that
can be transmitted at a time through the socket. You may set it
to any power-of-2 value. However, what value you set depends
on your requirements.
<b>addr</b>: addr is a two-element tuple, the first element
being host and the second element as port. The addr variable
will be made use of when sending messages to the server.
Once we have set the socket parameters using different variables, we can now actually initialize the socket, i.e.
create the socket as follows:
UDPSock = socket(AF_INET,SOCK_DGRAM)
Note that the above code fragment does not use any of the variables that we have initialized before. However,
those variables are required when actually sending the message to the server. In the above code fragment,
SOCK_DGRAM indicates that we are using the UDP protocol for communication.
Now that we have created the socket, we can now send a message to the server using the socket object's
sendto() method :
msg = "Whatever message goes here..."
UDPSock.sendto(data,addr)
Thus we have created the client program. Now let us create the server program that will display the messages that
the client has sent.
Server Program
In the server program also, we create the socket in a similar manner, i.e., first we initialize our variables:
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
Now we have to create the socket, which again is similar to the client program:
UDPSock = socket(AF_INET,SOCK_DGRAM)
Another piece of code that needs to be added to the server code when creating the socket, is that we need to bind
the address, addr, to the socket just created:
UDPSock.bind(addr)
<b>addr</b>: This is the local host bind port and should be
same as the addr value passed in the client program.
Now after creating the socket, we can now receive messages sent by the client using the socket object's
recvfrom() method :
data,addr = UDPSock.recvfrom(buf)
Note that in the above code fragment, UDPSock.recvfrom() takes the buffer size, buf, as an argument and
returns a tuple of two elements; thus we assign the values of the tuple to two variables, data and addr. We can
now print the data received as:
print data
Thus we have created the server program. Now the client can communicate with server using a socket. Note that
for the server to receive messages from the client, it (the server) should be running while the message is being
sent by the client.
In the sections that follow, the codes for the client and server programs using Python have been listed. The codes
are self-explanatory.
Client program code
# Client program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg
# Send messages
while (1):
data = raw_input('>> ')
if not data:
break
else:
if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'....."
# Close socket
UDPSock.close()
We have refined the client program so that it accepts inputs from the keyboard, which is transmitted
(communicated through sockets) to the server. A return (pressing enter/return once) will exit the client program.
Server program code
# Server program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"'"
# Close socket
UDPSock.close()
We have refined the server program so that as and when the client sends a message, the server keeps displaying
it.
Interactive session
The following screenshots illustrate an interactive client-server communication using sockets (in Python):
Client sending messages
Server receiving messages
Conclusion
Thus we have learned how to communicate to a server from a client using sockets in Python. There are several
applications that can be created using sockets, mostly network communication related applications. One popular
example where sockets are used is in chat applications. In a typical chat application, each client is a server as well,
and each server is a client as well, i.e., clients need to be able to listen and servers need to be able to transmit
data.
If you have any comments/suggestions, please do get in touch with me.