Simplest chat room using python

The Simplest you can build

Ecnivs
2 min readNov 12, 2022

Introduction

This article demonstrates how to build the simplest chat room using python. The code uses a server script that allows a client script to connect with the help of sockets.

Socket Programming

Sockets can be thought of as endpoints in a communication channel that is bi-directional and establishes communication between a server and client.

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. In our case we will be using localhost.

import socket

# Server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 9999))

server.listen()
client, addr = server.accept() # Accept connections

done = False

while not done:
# Decode and Encode messages
msg = (client.recv(1024).decode('utf-8'))
if msg == 'quit':
done = True
else:
print(msg)
client.send(input("Message: ").encode('utf-8'))

client.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. The exchange of messages will begin once connected.

import socket

# Client socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 9999))

done = False

while not done:
# Encode and Decode messages
client.send(input("Message: ").encode("utf-8"))
msg = client.recv(1024).decode("utf-8")
if msg =="quit":
done = True
else:
print(msg)


client.close()
Output

--

--