Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Simple Chat Room using Python
In this article we will see how to make a server and client chat room system using Socket Programming with Python.
The sockets are the endpoints of any communication channel. These are used to connect the server and client. Sockets are Bi-Directional. In this tutorial, we will setup sockets for each end and create a chatroom system among different clients through the server. The server side has some ports to connect with client sockets. When a client tries to connect with the same port, then the connection will be established for the chat room.
There are basically two parts: the server side and the client side. When the server side script is running, it waits for any active connection request. When one connection is established, it can communicate with it.
In this case we are using localhost. If machines are connected via LAN, then we can use IP addresses to communicate. The server will display its IP, and ask for a name for the server. From the client side, we have to mention a name, and also the IP address of the server to connect.
The Server Side Code
The server creates a socket, binds it to a port, and waits for incoming connections ?
import time, socket, sys
print('Setup Server...')
time.sleep(1)
# Get the hostname, IP Address from socket and set Port
soc = socket.socket()
host_name = socket.gethostname()
ip = socket.gethostbyname(host_name)
port = 1234
soc.bind((host_name, port))
print(host_name, '({})'.format(ip))
name = input('Enter name: ')
soc.listen(1) # Try to locate using socket
print('Waiting for incoming connections...')
connection, addr = soc.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[1]))
# Get a connection from client side
client_name = connection.recv(1024)
client_name = client_name.decode()
print(client_name + ' has connected.')
print('Press [bye] to leave the chat room')
connection.send(name.encode())
while True:
message = input('Me > ')
if message == '[bye]':
message = 'Good Night...'
connection.send(message.encode())
print("\n")
break
connection.send(message.encode())
message = connection.recv(1024)
message = message.decode()
print(client_name, '>', message)
The Client Side Code
The client connects to the server using the server's IP address and port number ?
import time, socket, sys
print('Client Server...')
time.sleep(1)
# Get the hostname, IP Address from socket and set Port
soc = socket.socket()
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
# Get information to connect with the server
print(shost, '({})'.format(ip))
server_host = input('Enter server's IP address: ')
name = input('Enter Client's name: ')
port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
while True:
message = soc.recv(1024)
message = message.decode()
print(server_name, ">", message)
message = input(str("Me > "))
if message == "[bye]":
message = "Leaving the Chat room"
soc.send(message.encode())
print("\n")
break
soc.send(message.encode())
How It Works
The communication flow works as follows:
- Server Setup: The server creates a socket, binds it to a hostname and port, then listens for connections
- Client Connection: The client creates a socket and connects to the server using its IP address
- Name Exchange: Both parties exchange their names for identification in the chat
- Message Loop: Server and client alternate sending and receiving messages until one types "[bye]"
Key Points
- Both scripts use port
1234for communication - Messages are encoded/decoded using UTF-8
- The chat ends when either party sends "[bye]"
- This is a simple one-to-one chat system (server can handle only one client at a time)
Running the Chat Room
To test the chat room:
- First run the server script
- Note the displayed IP address
- Run the client script and enter the server's IP address
- Start chatting! Type "[bye]" to exit
Conclusion
This simple chat room demonstrates basic socket programming concepts in Python. The server listens for connections while the client initiates communication, creating a bidirectional message exchange system using TCP sockets.
