Distributed Chat System with Offensive Content Monitoring

Soban Malik
7 min readJan 28, 2025

Overview
The Distributed Chat System facilitates communication between clients via a central server. The server acts as a mediator, forwarding messages between clients while monitoring their content for offensive or inappropriate language. If offensive content is detected, the server issues a warning to the sender and logs the incident for monitoring purposes.

Features

  1. Distributed Communication: Enables real-time messaging between clients connected to the server.
    2. Content Moderation: Monitors messages for offensive or inappropriate
    language using a predefined dictionary.
    3. Logging: Logs user details, messages, and timestamps for monitoring and auditing.
    4. Multi-threading: Supports multiple clients simultaneously using threading.
    5. Platform Independence: Clients and servers can operate on different physical machines.

System Components

Server
The server handles client connections, message forwarding, content moderation, and logging.

Functionalities:

  1. Client Connection Management:
    ○ Accepts multiple client connections using threading.
    ○ Maintains a list of connected clients.
    2. Message Handling:
    ○ Receives messages from clients.
    ○ Checks messages for offensive content.
    ○ Forwards non-offensive messages to other clients.
    3. Content Moderation:
    ○ Uses exact and approximate matching to detect offensive words.
    ○ Warns clients by sending offensive messages.
    4. Logging:
    ○ Logs sender details, messages, and timestamps in server_log.txt .

Code:

import socket # Module for creating network connections
import threading # Module for handling multiple client connections concurrently
import datetime # Module for logging timestamped messages
import re # Module for regular expressions to find patterns in text
from difflib import get_close_matches # Module for approximate string matching
# Dictionary containing offensive words categorized by language or type
OFFENSIVE_WORDS = {
"english": [
"bad", "dirty", "offensive", "stupid", "idiot", "fool", "hate", "ugly", "dumb", "lazy",
"nonsense", "crazy", "donkey", "annoying", "liar", "cheat", "failure", "useless",
"worthless", "trash", "boring", "crap", "disgusting", "pathetic", "dog"
],
"urdu": [
"bakwas", "chawal", "ghalat", "bevakoof", "nalayak", "chor", "kamina", "kutta",
"ganda",
"bakri", "langoor", "bewakoof", "lota", "chor", "laalchi", "kamchor"
],
"pashto": [
"badmash", "laar", "kamzay", "nakhrebaaz", "paagal", "begherat", "khar", "zeerak",
"shaitan", "kamkaar", "khocha", "zhwand", "luchak", "paighla", "zorawar", "kapray",
"garzan"
],
"romanized": [
"tumhe sharam nahi", "chup kar", "bakwas band karo", "ghar jao",
"ghalat baat", "sharam karo", "dheet insan",
"tameez seekho", "har waqt bakwas", "pagal ho tum", "batameezi mat karo",
"taso laka khar ye", "sta khabara galat da", "sta laara na da", "sta akhlaaq na di",
"sta pa khabar sm", "taso waak ye", "sta zehr d sho", "sta kho poy na ye", "sta da
tabahi"
,
"jahil", "zehar", "behooda", "fazool", "shakal dekhi hai apni", "kaam chor",
"bakwas mat karo", "dimagh mat kharab karo", "ganda insan", "chichora", "nakhre",
"badtameez", "nikamma", "kaam ka nahi", "besharam", "lafanga", "badtameez
insaan"
,
"pagal admi"
]
}
# Combine all offensive words from different categories into a single flat list
FLATTENED_OFFENSIVE_WORDS = [word for sublist in
OFFENSIVE_WORDS.values() for word in sublist]
# List to store connected clients and their addresses
clients = []
def log_message(sender_address, message):
"""Log messages from clients into a file with a timestamp."""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Current
time
log_entry = f"{timestamp} - {sender_address} - {message}\n" # Format log entry
with open("server_log.txt", "a") as log_file: # Open log file in append mode
log_file.write(log_entry) # Write the log entry to the file
def contains_offensive_content(message):
"""
Check if the message contains offensive words using exact and approximate
matching.
"""

normalized_message = message.lower() # Convert the message to lowercase for
comparison
# Check for exact matches using regular expressions
for word in FLATTENED_OFFENSIVE_WORDS:
if re.search(rf"\b{word}\b", normalized_message): # Match whole words only
return True
# Check for approximate matches (e.g., handling typos)
words_in_message = re.findall(r"\w+", normalized_message) # Extract words from
the message
for msg_word in words_in_message:
if get_close_matches(msg_word, FLATTENED_OFFENSIVE_WORDS, n=1,
cutoff=0.8): # Match similar words
return True
return False # No offensive content detected
def handle_client(client_socket, client_address):
"""Handle communication with a single client."""
print(f"Client connected: {client_address}") # Notify server about the new connection
clients.append((client_socket, client_address)) # Add client to the list of connected
clients
while True:
try:
# Receive a message from the client
message = client_socket.recv(1024).decode("utf-8")
if not message: # If no message is received, break the loop
break
print(f"Message from {client_address}: {message}") # Display the message on
the server
log_message(client_address, message) # Log the message to a file
# Check if the message contains offensive content
if contains_offensive_content(message):
warning = "Warning: Your message contains inappropriate content and was
not delivered."

client_socket.send(warning.encode("utf-8")) # Send warning to the client
else:
# Forward the message to other connected clients
for other_client, other_address in clients:
if other_client != client_socket: # Exclude the sender
forward_message = f"From {client_address}: {message}"
other_client.send(forward_message.encode("utf-8")) # Send the
message
except Exception as e:
print(f"Error with {client_address}: {e}") # Log any errors
break
print(f"Client disconnected: {client_address}") # Notify about client disconnection
clients.remove((client_socket, client_address)) # Remove the client from the list
client_socket.close() # Close the client's socket
def start_server(host="0.0.0.0", port=5555):
"""Start the chat server."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a TCP
socket
server.bind((host, port)) # Bind the socket to the specified host and port
server.listen(5) # Start listening for connections (allow up to 5 simultaneous clients)
print(f"Server started on {host}:{port}") # Notify that the server is running
while True:
client_socket, client_address = server.accept() # Accept a new client connection
# Handle the new client in a separate thread
client_thread = threading.Thread(target=handle_client, args=(client_socket,
client_address))
client_thread.start()
if __name__ == "__main__":
start_server() # Start the server

Clients
The clients connect to the server to send and receive messages.

Functionalities:

  1. Server Connection:
    ○ Establishes a TCP connection to the server.
    2. Message Sending:
    ○ Allows the user to input and send messages.
    3. Message Receiving:
    ○ Continuously listens for messages from the server.

Code:

import socket # Module for creating network connections
import threading # Module for handling concurrent message receiving
def receive_messages(client_socket):
"""
Function to continuously receive messages from the server.
"""

while True:
try:
# Receive and decode the message from the server
message = client_socket.recv(1024).decode("utf-8")
if message:
print(f"\n{message}") # Print the received message
except Exception as e:
# Handle connection errors and exit the loop
print(f"Connection error: {e}")
break
def start_client(server_ip, server_port):
"""
Function to connect to the server and handle client-side communication.
"""

# Create a TCP socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Attempt to connect to the server
client.connect((server_ip, server_port))
print(f"Connected to server at {server_ip}:{server_port}")
# Start a separate thread to handle receiving messages
receive_thread = threading.Thread(target=receive_messages, args=(client,))
receive_thread.start()
while True:
try:
# Prompt the user to enter a message
message = input("Enter your message (type 'exit' to quit): ")
if message.lower() == "exit": # Check if the user wants to quit
print("Exiting...")
break
# Send the user's message to the server
client.send(message.encode("utf-8"))
except Exception as e:
# Handle errors during message sending
print(f"Error: {e}")
break
# Close the socket connection after exiting
client.close()
if __name__ == "__main__":
# Define the server's IP address and port (replace with actual server details)
SERVER_IP = "192.168.142.131" # the server's IP address (This is the server IP
that i run on Virtual Machine)
SERVER_PORT = 5555
# Start the client and connect to the server
start_client(SERVER_IP, SERVER_PORT)

Usage Instructions

  1. Server Setup:
    ○ Run the server code on a machine accessible to all clients.
    ○ Ensure the server machine’s IP address and port are shared with clients.
    2. Client Setup:
    ○ Run the client code on different machines.
    ○ Update the server IP and port in the client code.
    3. Communication:
    ○ Clients can send messages to the server, which forwards them to other
    clients.
    ○ Offensive content will be blocked, and the sender will receive a warning.

Log File Structure
The server creates a log file named server_log.txt, with entries in the following format:

YYYY-MM-DD HH:MM:SS - (Client_IP, Client_Port) - Message_Content

Key Considerations

  1. Scalability: The server can handle multiple clients but is limited by system resources.
    2. Security: Sensitive data such as IP addresses should be protected.
    3. Future Enhancements:
    ○ Add encryption for secure communication.
    ○ Use a database for efficient log storage.

Result and Screenshots

Server Output
● Server successfully starts and logs client connections.

● Displays incoming messages and logs them in the log file.

Client Output
● Clients successfully connect to the server.

● Can send and receive messages

● Receive warnings for inappropriate content.

Example Screenshots:

  1. Server Log: A screenshot showing the server log file (server_log.txt) with time-stamped entries.

2. Client Warning: A screenshot showing the client receiving a warning for
offensive content.

3. Message Exchange: A screenshot of two clients exchanging messages via the server.

Conclusion
This system provides a robust solution for distributed messaging with built-in content moderation and logging. It suits environments requiring controlled communication, such as educational platforms or workplace chat systems.

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

Soban Malik
Soban Malik

No responses yet

Write a response