Building a Chat Server and Client in Python with Socket Programming

Shikha Pandey
5 min readJul 3, 2023

--

Introduction:

In this article, we’ll explore the exciting world of socket programming by creating a simple chat server and client application in Python.

Socket programming allows two devices to communicate over a network using sockets, which act as endpoints for sending and receiving data. Our chat application will allow multiple clients to connect to the server and exchange messages in real-time.

Prerequisites:

Before we get started, make sure you have Python 3.x installed on your system. You can download Python from the official website (https://www.python.org/downloads/).

Step 1: Setting up the Project

First, let’s create a new directory for our project and navigate into it:

mkdir chat_app
cd chat_app

Step 2: Implementing the Server

Create a new file called server.py and open it in your favorite text editor. We'll start by importing the necessary libraries:

import socket
import threading

Next, let’s define the server code. We’ll implement a function to handle each client’s connection and communication:

def handle_client(client_socket):
while True:
data = client_socket.recv(1024)
if not data:
break
message = data.decode('utf-8')
print(f"Received message: {message}")
response = "Server received your message: " + message
client_socket.sendall(response.encode('utf-8'))
client_socket.close()

In the handle_client function, we use a while loop to continuously receive data from the client. If the data received is empty, it means the client has disconnected, and we break out of the loop. Otherwise, we decode the received data and print it to the server’s console. Then, we construct a response message and send it back to the client.

Now, let’s create the main function to set up the server:

def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 12345
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Server listening on {host}:{port}")

while True:
client_socket, client_address = server_socket.accept()
print(f"Accepted connection from {client_address}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()

if __name__ == "__main__":
main()

In the main function, we start by creating a socket object called server_socket. This socket acts as a communication endpoint for the server. The socket function from the socket module is used to create this socket object. We pass two arguments to this function:

  1. socket.AF_INET: This argument specifies the address family for the socket, which, in this case, is the Internet Protocol version 4 (IPv4) addressing. It stands for "Address Family - Internet."
  2. socket.SOCK_STREAM: This argument specifies the socket type, which is TCP (Transmission Control Protocol) in this case. TCP is a reliable, connection-oriented protocol used for data transmission. It stands for "Socket Type - Stream."

By combining these two arguments, we create a new socket object that will be used for TCP communication over IPv4. This socket will be the server’s socket that listens for incoming connections from clients.

With this socket created and configured for TCP communication, the server can then proceed to bind it to a specific IP address (127.0.0.1) and port number (12345). After binding, the server is ready to listen for incoming connections from clients.

When a client connects, the server accepts the connection and creates a new thread to handle that client. The handle_client function is called in the new thread, allowing the server to handle multiple client connections concurrently.

Step 3: Implementing the Client

Next, create a new file called client.py and open it in your text editor. Similar to the server, start by importing the required library:

import socket
import threading

Next, implement the main function for the client:

def main():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 12345
client_socket.connect((host, port))

while True:
message = input("Enter your message: ")
client_socket.sendall(message.encode('utf-8'))
data = client_socket.recv(1024)
response = data.decode('utf-8')
print(f"Server response: {response}")

if __name__ == "__main__":
main()

In the main function, we create a client socket and connect it to the server's IP address (127.0.0.1) and port number (12345). Then, we enter into a loop, allowing the user to input messages and send them to the server using the sendall method. We also receive the server's response and display it to the client.

Step 4: Testing the Chat Application

Now, let’s test our chat application with some snapshots to see how it works.

  1. Start the server by running python server.py in the terminal:

2. Open a new terminal window and run the client script using python client.py:

3. The server terminal will show a message indicating that it has accepted the client connection:

4. To test with multiple clients, open more terminal windows and run client.py in each of them.

5. Once multiple clients are connected, the server terminal will display messages for each client connection:

In the above examples, I have created 3 instances

6. Send a message from one of the clients:

7. The server will receive the message and send a response back to the client.

[NOTE — ] The screenshots provided in the previous snapshot descriptions demonstrate how the terminal looks after performing the respective steps.

Conclusion:

In this tutorial, we’ve explored the fascinating world of socket programming by building a simple chat server and client application in Python. You have learned how to create a server that can handle multiple client connections concurrently and enable real-time communication between clients.

Socket programming is a fundamental concept in network programming and opens up a wide range of possibilities for developing various networked applications, including chat applications, multiplayer games, and more.

Feel free to further enhance this project according to your needs and creativity. You can add additional features, improve error handling, or create a more interactive user interface.

If you found this tutorial helpful, don’t forget to check out the source code on my GitHub repository: https://github.com/Shikha-code36/ChatServer_with_Socket_Python. I’d truly appreciate your support by giving it a star if you find it useful.

Thank you for joining me on this socket programming journey. I hope you’ve gained valuable insights into building networked applications using Python. Happy coding and networking!

If you have any questions or need further assistance, feel free to reach out to me via GitHub or my email [shikha.py36@gmail.com].

--

--

Shikha Pandey

Software Engineer - Tech Enthusiast - Startup Enthusiast. Reach me out at https://shikhapandey.me/:)