The Wayback Machine - https://web.archive.org/web/20240930233705/https://www.geeksforgeeks.org/simple-chat-room-using-python/
Open In App

Simple Chat Room using Python

Last Updated : 19 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article demonstrates – How to set up a simple Chat Room server and allow multiple clients to connect to it using a client-side script. The code uses the concept of sockets and threading. 
 

Socket programming

Sockets can be thought of as endpoints in a communication channel that is bi-directional and establishes communication between a server and one or more clients. Here, we set up a socket on each end and allow a client to interact with other clients via the server. The socket on the server side associates itself with some hardware port on the server-side. Any client that has a socket associated with the same port can communicate with the server socket. 
 

Multi-Threading

A thread is a sub-process that runs a set of commands individually of any other thread. So, every time a user connects to the server, a separate thread is created for that user, and communication from the server to the client takes place along individual threads based on socket objects created for the sake of the identity of each client. 
We will require two scripts to establish this chat room. One to keep the serving running, and another that every client should run in order to connect to the server. 
 

Server Side Script

The server-side script will attempt to establish a socket and bind it to an IP address and port specified by the user (windows users might have to make an exception for the specified port number in their firewall settings, or can rather use a port that is already open). The script will then stay open and receive connection requests and will append respective socket objects to a list to keep track of active connections. Every time a user connects, 
a separate thread will be created for that user. In each thread, the server awaits a message and sends that message to other users currently on the chat. If the server encounters an error while trying to receive a message from a particular thread, it will exit that thread. 
 

Usage

This server can be set up on a local area network by choosing any on the computer to be a server node, and using that computer’s private IP address as the server IP address. 
For example, if a local area network has a set of private IP addresses assigned ranging from 192.168.1.2 to 192.168.1.100, then any computer from these 99 nodes can act as a server, and the remaining nodes may connect to the server node by using the server’s private IP address. Care must be taken to choose a port that is currently not in usage. For example, port 22 is the default for ssh, and port 80 is the default for HTTP protocols. So these two ports preferably, shouldn’t be used or reconfigured to make them free for usage. 
However, if the server is meant to be accessible beyond a local network, the public IP address would be required for usage. This would require port forwarding in cases where a node from a local network (node that isn’t the router) wishes to host the server. In this case, we would require any requests that come to the public IP addresses to be re-routed towards our private IP address in our local network, and would hence require port forwarding. 
For more reading on port forwarding: link
To run the script, simply download it from the GitHub link specified at the bottom of the post, and save it at a convenient location on your computer. 

/* Both the server and client script can then be run
   from the Command prompt (in Windows) or from bash 
   Terminal (Linux users) by simply typing 
   "python chat_server.py  " or "python client.py  ". 
   For example, */
python chat_server.py 192.168.55.13 8081
python client.py 192.168.55.13 8081

Below is the Server side script that must be run at all times to keep the chatroom running.

Python3




# Python program to implement server side of chat room.
import socket
import select
import sys
'''Replace "thread" with "_thread" for python 3'''
from thread import *
 
"""The first argument AF_INET is the address domain of the
socket. This is used when we have an Internet Domain with
any two hosts The second argument is the type of socket.
SOCK_STREAM means that data or characters are read in
a continuous flow."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 
# checks whether sufficient arguments have been provided
if len(sys.argv) != 3:
    print ("Correct usage: script, IP address, port number")
    exit()
 
# takes the first argument from command prompt as IP address
IP_address = str(sys.argv[1])
 
# takes second argument from command prompt as port number
Port = int(sys.argv[2])
 
"""
binds the server to an entered IP address and at the
specified port number.
The client must be aware of these parameters
"""
server.bind((IP_address, Port))
 
"""
listens for 100 active connections. This number can be
increased as per convenience.
"""
server.listen(100)
 
list_of_clients = []
 
def clientthread(conn, addr):
 
    # sends a message to the client whose user object is conn
    conn.send("Welcome to this chatroom!")
 
    while True:
            try:
                message = conn.recv(2048)
                if message:
 
                    """prints the message and address of the
                    user who just sent the message on the server
                    terminal"""
                    print ("<" + addr[0] + "> " + message)
 
                    # Calls broadcast function to send message to all
                    message_to_send = "<" + addr[0] + "> " + message
                    broadcast(message_to_send, conn)
 
                else:
                    """message may have no content if the connection
                    is broken, in this case we remove the connection"""
                    remove(conn)
 
            except:
                continue
 
"""Using the below function, we broadcast the message to all
clients who's object is not the same as the one sending
the message """
def broadcast(message, connection):
    for clients in list_of_clients:
        if clients!=connection:
            try:
                clients.send(message)
            except:
                clients.close()
 
                # if the link is broken, we remove the client
                remove(clients)
 
"""The following function simply removes the object
from the list that was created at the beginning of
the program"""
def remove(connection):
    if connection in list_of_clients:
        list_of_clients.remove(connection)
 
while True:
 
    """Accepts a connection request and stores two parameters,
    conn which is a socket object for that user, and addr
    which contains the IP address of the client that just
    connected"""
    conn, addr = server.accept()
 
    """Maintains a list of clients for ease of broadcasting
    a message to all available people in the chatroom"""
    list_of_clients.append(conn)
 
    # prints the address of the user that just connected
    print (addr[0] + " connected")
 
    # creates and individual thread for every user
    # that connects
    start_new_thread(clientthread,(conn,addr))    
 
conn.close()
server.close()


Client-Side Script

The client-side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the user enters to the server for it to be broadcasted to other users.
This is the client-side script, that each user must use in order to connect to the server.
 

Python3




# Python program to implement client side of chat room.
import socket
import select
import sys
 
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
    print ("Correct usage: script, IP address, port number")
    exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
 
while True:
 
    # maintains a list of possible input streams
    sockets_list = [sys.stdin, server]
 
    """ There are two possible input situations. Either the
    user wants to give manual input to send to other people,
    or the server is sending a message to be printed on the
    screen. Select returns from sockets_list, the stream that
    is reader for input. So for example, if the server wants
    to send a message, then the if condition will hold true
    below.If the user wants to send a message, the else
    condition will evaluate as true"""
    read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
 
    for socks in read_sockets:
        if socks == server:
            message = socks.recv(2048)
            print (message)
        else:
            message = sys.stdin.readline()
            server.send(message)
            sys.stdout.write("<You>")
            sys.stdout.write(message)
            sys.stdout.flush()
server.close()


Output: 

In the picture given below, a server has been initialized on the left side of the terminal and a client script on the right side of the terminal. (Splitting of terminal done using tmux, ‘sudo apt-get install tmux’). For initialization purposes, you can see that whenever a message is sent by a user, the message along with IP address is shown on the server-side. 
 

Screenshot from 2017-04-18 18-31-03

The below picture has a basic conversation between two people on the same server. Multiple clients can connect to the server in the same way! 
 

Screenshot from 2017-04-18 18-31-03

Link to download script: link

 



Similar Reads

Simple chat Application using Websockets with FastAPI
In this article, we'll delve into the concept of WebSockets and their role in facilitating bidirectional communication between clients and servers. Subsequently, we'll embark on the journey of building a real-time multi-client chat application. This application will empower numerous users to connect to the server via the WebSocket protocol, fosteri
6 min read
Searching Hotel Room Project in Django
In this article, we'll explore a technique for efficiently organizing and displaying images or information based on specific parameters. Our goal is to make it easy for users to sort images according to their preferences, particularly by price, with a single click. This project simplifies the process of arranging images or data in both ascending an
6 min read
Converting WhatsApp chat data into a Word Cloud using Python
Let us see how to create a word cloud using a WhatsApp chat file. Convert the WhatsApp chat file from .txt format to .csv file. This can be done using Pandas. Create a DataFrame which read the .txt file. The .txt file had no columns like it is in an .csv file. Then, split the data into columns by separating them and giving each column a name. The f
4 min read
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that customer is no longer required to follow the same tradi
7 min read
Export WhatsApp Chat History to Excel Using Python
In this article, we will discuss how to export a specific user's chats to an Excel sheet. To export the chats, we will use several Python modules and libraries. In the Excel file, we will create four columns: Date, Time, Name, and Message. We'll create these columns through Pandas, export all the chat details to their respective columns, and use Pu
5 min read
Realtime chat app using Django
Chat Room has been the most basic step toward creating real-time and live projects. The chat page that we will create will be a simple HTML boilerplate with a simple h1 text with the name of the current user and a link to log out to the user who is just logged in. You may need to comment on the line until we create auth system for this. This ensure
11 min read
Chat Bot in Python with ChatterBot Module
Nobody likes to be alone always, but sometimes loneliness could be a better medicine to hunch the thirst for a peaceful environment. Even during such lonely quarantines, we may ignore humans but not humanoids. Yes, if you have guessed this article for a chatbot, then you have cracked it right. We won't require 6000 lines of code to create a chatbot
3 min read
Simple registration form using Python Tkinter
Prerequisites: Tkinter Introduction, openpyxl module.Python provides the Tkinter toolkit to develop GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit. Let's make a simple information form GUI application using Tkinter. In this application, User has to fill up the required info
5 min read
Python | Simple GUI calculator using Tkinter
Prerequisite: Tkinter Introduction, lambda function Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI a
6 min read
Python | Simple FLAMES game using Tkinter
Prerequisites: Introduction to TkinterProgram to implement simple FLAMES game Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and e
5 min read
Python | Simple calculator using Tkinter
Prerequisite : Tkinter IntroductionPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Cr
3 min read
Python | Make a simple window using kivy
Kivy is a platform independent as it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it Does not mean that it can not be used on Desktops applications. Use this command To install kivy: pi
5 min read
Python | Thresholding techniques using OpenCV | Set-1 (Simple Thresholding)
Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255). Thresholding is a very popular
3 min read
Python - Convert simple lines to bulleted lines using the Pyperclip module
Pyperclip is the cross-platform Python module which is used for copying and pasting the text to the clipboard. Let's suppose you want to automate the task of copying the text and then convert them to the bulleted points. This can be done using the pyperclip module. Consider the below examples for better understanding. Examples: Clipboard Content :
2 min read
Simple Plot in Python using Matplotlib
Matplotlib is a Python library that helps in visualizing and analyzing the data and helps in better understanding of the data with the help of graphical, pictorial visualizations that can be simulated using the matplotlib library. Matplotlib is a comprehensive library for static, animated and interactive visualizations. Installation of matplotlib l
5 min read
Build a simple Quantum Circuit using IBM Qiskit in Python
Qiskit is an open source framework for quantum computing. It provides tools for creating and manipulating quantum programs and running them on prototype quantum devices on IBM Q Experience or on simulators on a local computer. Let's see how we can create simple Quantum circuit and test it on a real Quantum computer or simulate in our computer local
5 min read
Simple Port Scanner using Sockets in Python
Prerequisites: Socket Programming in Python Before going to the programming, let us discuss about ports. In this article, we will check the virtual ports of a server or websites, or localhost. Every port has a unique number. There are 65,535 ports available in a host starting from 0. We can assign the ports for any services. Example 1: In this prog
3 min read
Create a Simple Two Player Game using Turtle in Python
Prerequisites: Turtle Programming in Python TurtleMove game is basically a luck-based game. In this game two-players (Red & Blue), using their own turtle (object) play the game. How to play The game is played in the predefined grid having some boundaries. Both players move the turtle for a unit distance.Now both players flip the coin:if HEAD, t
4 min read
Setting up a simple HTTP server using Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation On the terminal run the following stateme
2 min read
Building a Simple Application using KivyMD in Python
KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we will see how to make a simple application in KivyMD using Screen, Label, TextFieldInput, and Bu
3 min read
Simple BMI calculator using Python
In this article, we will guide you through the process of building a straightforward Body Mass Index (BMI) calculator using Python. To enhance user interaction, we will implement a simple graphical user interface (GUI) form. This form will allow users to input their weight and height, and with the help of the Django Framework, the BMI will be autom
4 min read
Generate simple ASCII tables using prettytable in Python
Prettytable is a Python library used to print ASCII tables in an attractive form and to read data from CSV, HTML, or database cursor and output data in ASCII or HTML. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border.  Installation In order to be able to use prettytable libra
5 min read
Simple Chatbot application using Python, GoogleAPIKey
Google-GenerativeAI is Google AI Python SDK. It uses Gemini to build AI-powered features. In this article, we will see how to create a Simple Chatbot application using Python GoogleAPIKey. What is Google-GenerativeAI?Google-GenerativeAI is nothing but Google AI Python SDK. It enables to use of Gemini to build AI-powered features and applications. T
4 min read
Create simple Blockchain using Python
Blockchain is a time-stamped decentralized series of fixed records that contains data of any size is controlled by a large network of computers that are scattered around the globe and not owned by a single organization. Every block is secured and connected with each other using hashing technology which protects it from being tampered by an unauthor
8 min read
Creating a simple browser using PyQt5
In this article we will see how we can create a simple browser using PyQt5. Web browser is a software application for accessing information on the World Wide Web. When a user requests a web page from a particular website, the web browser retrieves the necessary content from a web server and then displays the page on the screen. PyQt5 is cross-platf
4 min read
Create a Simple Sentiment Analysis WebApp using Streamlit
In this article, we will see how we can create a simple Sentiment Analysis webApp using with the help of Streamlit Module in Python. Required Modules: For this, we will need Three Modules. StreamlitTextBlobStreamlit_extras (optional). The module Streamlit_extras is optional because it will be used to add some extra features which will not affect th
4 min read
Python | Program to implement simple FLAMES game
Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame. FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately
6 min read
Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton
Tkinter is a GUI (Graphical User Interface) module which comes along with the Python itself. This module is widely used to create GUI applications. tkinter.ttk is used to create the GUI applications with the effects of modern graphics which cannot be achieved using only tkinter. Checkbutton is used to select multiple options. Checkbuttons can be cr
2 min read
Python | Create simple animation for console-based application
As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility. We will try to replicate the loading animation as shown below: We will be using following modules - sys mo
2 min read
Python | Creating a Simple Drawing App in kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Drawing App: In this we are going to create a simple drawing App with th
4 min read
Article Tags :
Practice Tags :