Skip to content

About

A terminal-based chat application built with Java sockets.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

Socket-Based Chat Application (Upgraded Architecture)

A robust, terminal-based multi-client chat application built in Java, upgraded with production-level concurrent architecture, thread pooling, domain-driven OOP messaging, structured diagnostic logging, and persistent SQL database storage.


🌟 Key Features

  1. Thread Pool (ExecutorService)

    • Eliminates thread explosion by replacing the naive thread-per-client model with a managed, bounded thread pool (Executors.newFixedThreadPool(50)).
    • Improves server scalability and resource efficiency under concurrent load.
    • Includes graceful shutdown hooks (Runtime.getRuntime().addShutdownHook) to cleanly terminate active worker threads and close sockets.
  2. Thread-Safe Client Management (ConcurrentHashMap)

    • Replaced coarse-grained synchronized collections with ConcurrentHashMap<String, ClientHandler>.
    • Atomic Registration: Utilizes putIfAbsent loops to guarantee collision-free username allocation without locking the entire server.
    • Atomic Renaming: Changes usernames atomically with putIfAbsent and conditional removal.
    • Instant Direct Messaging: $O(1)$ client lookup for private messaging (/msg).
  3. Structured Diagnostic Logging (ServerLogger)

    • Standardized console and audit logs tagged with clear contextual markers:
      • [CONNECT] User connection and remote IP address.
      • [DISCONNECT] User disconnect and reason.
      • [MSG] Public and direct message audit trail (sender -> receiver: content).
      • [COMMAND] Slash command invocation (/online, /rename, /help, etc.).
      • [DB] Database transactions, user upserts, and history retrieval.
      • [ERROR] Contextual error and exception traces.
  4. Object-Oriented Message Model (Message.java)

    • Replaced fragile string splitting with a domain entity Message (MessageType, sender, receiver, content, timestamp).
    • Clean wire-protocol serialization and parsing with delimiter escaping.
    • Enhanced client UI with ANSI color highlighting for history replay, direct messages, and system alerts.
  5. Database Persistence & History Replay (SQLite JDBC & DAO)

    • Persistent storage using embedded SQLite (chat.db).
    • Tables for users (registration and last_seen presence) and messages (chat log).
    • Asynchronous Persistence: Non-blocking message insertion via a dedicated single-thread DB executor.
    • Chat History on Login: Automatically loads and displays the last 30 messages to newly connected clients.

📁 Project Structure

c:\Socket-Based-Chat-Application\
├── lib\
│   ├── sqlite-jdbc-3.45.1.0.jar   # SQLite JDBC Driver
│   ├── slf4j-api-2.0.12.jar       # SLF4J Logging API
│   └── slf4j-simple-2.0.12.jar    # SLF4J Simple Implementation
├── src\
│   ├── Message.java               # OOP Message domain entity & wire protocol
│   ├── ServerLogger.java          # Structured diagnostic logger
│   ├── DatabaseManager.java       # SQLite JDBC persistence & history DAO
│   ├── ChatServer.java            # Server bootstrap, ExecutorService & ConcurrentHashMap
│   ├── ChatClient.java            # Client terminal with ANSI formatting & history display
│   └── Main.java                  # Project info & launcher instructions
├── chat.db                        # SQLite Database file (generated automatically)
└── README.md

🗄️ Database Schema

CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    first_seen TEXT NOT NULL,
    last_seen TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    type TEXT NOT NULL,
    sender TEXT NOT NULL,
    receiver TEXT NOT NULL,
    content TEXT NOT NULL,
    timestamp TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_messages_id ON messages(id DESC);

🚀 How to Compile & Run

1. Compile the Project

Open a terminal in the project directory:

javac -cp "src;lib/*" src/*.java

2. Start the Chat Server

In one terminal:

java -cp "src;lib/*" ChatServer

3. Start a Chat Client

In another terminal (run multiple times for multiple users):

java -cp "src;lib/*" ChatClient

💬 Client Commands

Inside the chat client, you can use:

  • hello everyone — Send a public message to all users
  • /msg <username> <message> — Send a private message to a specific user
  • /online — List all online users
  • /rename <newName> — Change your display name
  • /help — Display available commands
  • /exit — Disconnect from the server

About

A terminal-based chat application built with Java sockets.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages