Python 3 socket programming example

When it comes to network programming Python is a gem, not that it is not good at other stuffs but network programming is handled by Python exceedingly well and it makes it really easy to code and debug. I have named the title as Python 3 as there are few changes in Python 3 that affects many available socket programming tutorials on the internet. Before we dive deeper let’s clarify few terminologies.

Socket: A socket is an endpoint for communication between two machines. Yes as the name suggests socket is nothing but a pipe that will deliver the stuff from one end to another end. The medium can be the Local Area Newtork, Wide Area Network or the Internet. Sockets can use both TCP and UDP protocols.

The W3C website has a very good detailed description with example code for sockets here

Server: A server is a machine that waits for client requests and serves or processes them.

Client: A client on the other hand is the requester of the service.

What we are building? Well we are building a simple server and a client where server will open a socket and wait for clients to connect. Once client is connected he can send a message and server will process the message and reply back the same message but converted into upper case to demonstrate the server side processing and transmission. Conceptually this sounds fairly simple and so it is implementation-wise also. Without further ado let’s look at the code first. Then we will go through what they are doing

We will create two files:

  • server.py
  • client.py

As the name suggests the server.py will hold the server code that will listen for client connection and client.py will hold the client code


import socket

def Main():
	host = "127.0.0.1"
	port = 5000
	
	mySocket = socket.socket()
	mySocket.bind((host,port))
	
	mySocket.listen(1)
	conn, addr = mySocket.accept()
	print ("Connection from: " + str(addr))
	while True:
			data = conn.recv(1024).decode()
			if not data:
					break
			print ("from connected  user: " + str(data))
			
			data = str(data).upper()
			print ("sending: " + str(data))
			conn.send(data.encode())
			
	conn.close()
	
if __name__ == '__main__':
	Main()

What the code is doing ?

  1. First we import the python socket library.
  2. Then we define a main function
  3. We define two variables, a host and a port, here the local machine is the host thus ip address of 127.0.0.1 & I have chosen randomly port 5000 and it is advised to use anything above 1024 as upto 1024 core services use the ports
  4. Then we define a variable mySocket which is an instance of a Python socket
  5. In server it is important to bind the socket to host and port thus we bind it, tip: bind takes a Tuple, thus we have double brackets surrounding it
  6. Then we call the listen method and pass 1 to it so that it will perpetually listen till we close the connection
  7. Then we have two variables conn and addr which will hold the connection from client and the address of the client
  8. Then we print the clients address and create another variable data which is receiving data from connection and we have to decode it, this step is necessary for Python 3 as normal string with str won’t pass through socket and str does not implement buffer interface anymore.
  9. We run all this in a while true loop so unless the the connection is closed we run this and server’s keeps on listening when the data is received server transforms in into uppercase by calling upper method and sends the string back to client and we encode too as normal string will fail to transmit properly

So that’s all that is there to the server.py file and I hope I was able to clarify each step.

Now let’s have a look at the client.py file


import socket

def Main():
		host = '127.0.0.1'
		port = 5000
		
		mySocket = socket.socket()
		mySocket.connect((host,port))
		
		message = input(" -> ")
		
		while message != 'q':
				mySocket.send(message.encode())
				data = mySocket.recv(1024).decode()
				
				print ('Received from server: ' + data)
				
				message = input(" -> ")
				
		mySocket.close()

if __name__ == '__main__':
	Main()

So what is exactly happening on the client file?

  1. Well similarly we import the socket module and create similar variable mySocket and connect via passing server’s address 127.0.0.1 and port 5000
  2. However, one noticeable difference is we do not have to add bind as client does not need to bind, this is a very basic yet important concept of network programming
  3. Then we use the input method to ask for input , see Python 3 has replaced raw_input by simply input
  4. Then while the character typed is not “q” we keep running the loop and send the message by encoding it and when we received the processed data we decode it and print
  5. One common thing is the main method of Python we run on both the files which is wrapped in the magic __main__ method to be run

That’s all is there to this simple programming. I hope this will clear the basic ideas on python socket programming and you can build better things from here on as the possibilities are immense. I have a tutorial on how to create a GUI python app using PyQt here perhaps you can use this tutorial in conjunction with that one and create a beautiful desktop multi-user chat client. For confirmation I attach the screenshot of the built app.

python socket

Thank you
Happy coding 🙂