A Beginner's Guide to Socket Programming in Python

Bilal K.
3 min readMar 9, 2024

Sockets are used to transmit messages between devices over local or global networks. Socket is an endpoint of communication and this is why sockets are helpful in real-time client-server applications that depend on instant message exchange, such as WhatsApp or Telegram. In simple terms, we can define a socket as a quick connection which allows the transmission of data between two processes on the same machine or different machines over a network.

random image from google.com

Typically, a socket program consists of two primary components: the client and the server. In this setup, the client acts as the requester, seeking specific data. The server acts as the listener and provides the client with the requested data as the response. For this blog, we’ll keep the things simple and explore how to use socket.py to listen to a host on a particular port and whatever message it receives, it will transmit back the same message to the client. Let’s dive in.

CREATING A SERVER SOCKET

To create a server socket, we’ll need to follow these steps:

  • Import the socket module.
  • Initializes a TCP server on localhost (127.0.0.1 )and port 8080 to listen on.
  • Listens for incoming client connections.
  • Accepts client connections and enters a loop for message exchange.
  • Sends “accepted” response to client messages, closes the connection gracefully upon receiving the req, closes the client connection and shuts down the server after communication ends.
import socket

def server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = "127.0.0.1"
server_port = 8080

# bind the socket to a specific address and port
server.bind((server_ip, server_port))
server.listen(0)
print(f"Listening on {server_ip}:{server_port}")

# Accept the incoming connection
client, addr = server.accept()
print(f"Accepted connection from {addr[0]}:{addr[1]}")

while True:
request = client.recv(1024).decode("utf-8")

# if we recieve "close" from the client, we close the connection
if request == "closed":
print("Closing the connection, bye!")
client.close()
break

print(f"Client: {request}")

response = "accepted".encode("utf-8") # converting string to bytes
client.send(response)

#close the connection
client.close()
print ("Connection closed")
#close the server
server.close()

server()

In the above code, we listen for incoming connections on localhost, port 8080. When a connection is established, it accepts it and enters a loop to handle communication with the client. The server continuously receives messages from the client, responding with ‘accepted’ to each message. If the client sends ‘closed’, indicating a desire to terminate the connection, the server closes the connection and exits the loop. Finally, it gracefully closes both the client connection and the server itself.

CREATING A CLIENT SOCKET

To create a client socket, we’ll follow these steps.

  • A function client() is defined that sets up a TCP socket client. Establishes a connection to a server at IP address “127.0.0.1” and port 8080.
  • Within a loop, it prompts the user to input a message, sends it to the server, and receives a response.
  • If the user inputs “close”, it closes the connection and exits the loop; otherwise, it continues sending and receiving messages.
import socket

def client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_ip = "127.0.0.1"
server_port = 8080

client.connect((server_ip, server_port))
print(f"Connected to {server_ip}:{server_port}")

while True:
message = input("Enter your message: ")
client.send(message.encode("utf-8")[:1024])

if message == "close":
print("Closing the connection from client, bye!")
client.close()
break

response = client.recv(1024).decode("utf-8")
print(f"Server: {response}")

print (f"Response: {response}")

client.close()
print ("Connection closed")

client()

The client-side code establishes a TCP socket client that connects to a server running on the local machine at IP address “127.0.0.1” and port 8080. It prompts the user to input messages, which are then sent to the server. If the user inputs “close”, the client gracefully closes the connection and exits the loop. Otherwise, it continues sending and receiving messages.

Conclusion

In this tutorial, we have explored how sockets are fundamental to computer networking and have learned to create a socket program in Python using the socket module for both client-side and server-side applications.

So that’s it! I hope you found it helpful, and also I hope that you have a nice day.

Till next time :) Happy Learning!

Bilal K.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Bilal K.
Bilal K.

Written by Bilal K.

Software Engineer, I share tips and tools to help fellow developers level up.

No responses yet

Write a response