0% found this document useful (0 votes)
15 views

Unit 7 Java Chatting Application

Uploaded by

Dr Nyongesa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 7 Java Chatting Application

Uploaded by

Dr Nyongesa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1|Page

CHAT APPLICATION
Introduction
Our chat application is a simple yet robust solution designed to facilitate real-time communication between

multiple users. Developed using Java, this application employs socket programming to create a central

server that manages connections from multiple clients (Mishra, T. 2019). Each client can send messages to

the server, which then broadcasts these messages to all other connected clients, ensuring seamless

communication. The user interface is text-based, providing a straightforward and efficient way for users to

input and receive messages. This application exemplifies the fundamental principles of network

programming and client-server architecture, making it an ideal project for understanding the basics of real-

time communication systems.

Chat Server Overview


The chat server is the core component of our application, responsible for managing multiple client

connections and ensuring efficient message distribution. Implemented in Java using socket programming,

the server listens for incoming connections on a specified port and assigns a unique user ID to each client. A

dedicated thread handles communication for each connected client, allowing simultaneous interactions

without blocking. The server maintains a list of active clients and uses a broadcast mechanism to relay

messages from one client to all others. This architecture ensures that the chat experience is real-time and

cohesive, providing a reliable platform for multi-user communication (Maruyama, H. 2002). By efficiently

managing resources and connections, the chat server demonstrates fundamental concepts of concurrent

programming and network communication, making it a valuable learning tool for understanding server-

client dynamics in a distributed environment.

package uoPeopleChatApplication;

import java.io.*;

import java.net.*;

import java.util.*;
2|Page

public class ChatServer {

private static int clientId = 0;

private static Set<ClientHandler> clientHandlers = new HashSet<>();

public static void main(String[] args) {

try (ServerSocket serverSocket = new ServerSocket(12345)) {

System.out.println("Chat server started on port 12345...");

while (true) {

Socket socket = serverSocket.accept();

clientId++;

ClientHandler clientHandler = new ClientHandler(socket, clientId);

clientHandlers.add(clientHandler);

new Thread(clientHandler).start();

} catch (IOException e) {

e.printStackTrace();

}
3|Page

public static void broadcastMessage(String message, ClientHandler sender) {

for (ClientHandler client : clientHandlers) {

if (client != sender) {

client.sendMessage(message);

public static void removeClient(ClientHandler clientHandler) {

clientHandlers.remove(clientHandler);

class ClientHandler implements Runnable {

private Socket socket;

private int clientId;

private PrintWriter out;

public ClientHandler(Socket socket, int clientId) {

this.socket = socket;

this.clientId = clientId;
4|Page

@Override

public void run() {

try {

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

out.println("Welcome! You are user #" + clientId);

String message;

while ((message = in.readLine()) != null) {

System.out.println("User #" + clientId + ": " + message);

ChatServer.broadcastMessage("User #" + clientId + ": " + message, this);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

socket.close();

} catch (IOException e) {
5|Page

e.printStackTrace();

ChatServer.removeClient(this);

public void sendMessage(String message) {

out.println(message);

Chat Client Overview


The chat client is an essential component that enables users to connect to the server and communicate in

real-time. Each client connects to the server using sockets, ensuring a stable and persistent connection. The

text-based user interface allows users to easily input and send messages, which are then broadcast to all

other connected clients by the server. This setup supports multiple users simultaneously, ensuring a dynamic

and interactive chat environment. The client is designed to handle incoming messages efficiently, displaying

them promptly to the user. By leveraging Java’s socket programming capabilities, the chat client provides a

seamless and responsive communication experience, highlighting the principles of client-server architecture

and multi-threaded programming. This allows for a scalable and robust solution suitable for various real-

time communication needs.

package uoPeopleChatApplication;

import java.io.*;
6|Page

import java.net.*;

public class ChatClient {

private Socket socket;

private BufferedReader in;

private PrintWriter out;

public ChatClient(String serverAddress, int serverPort) {

try {

// Connect to the server

socket = new Socket(serverAddress, serverPort);

// Set up input and output streams

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

// Start a thread to handle incoming messages

new Thread(new IncomingMessagesHandler()).start();

// Read user input from console and send it to the server

BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));


7|Page

String userInput;

while ((userInput = keyboardInput.readLine()) != null) {

out.println(userInput); // Send message to server

} catch (IOException e) {

e.printStackTrace();

// Inner class to handle incoming messages

private class IncomingMessagesHandler implements Runnable {

@Override

public void run() {

try {

String message;

while ((message = in.readLine()) != null) {

System.out.println(message); // Print incoming messages to console

} catch (IOException e) {

e.printStackTrace();

} finally {
8|Page

try {

socket.close(); // Close socket when done

} catch (IOException e) {

e.printStackTrace();

// Main method to start the client

public static void main(String[] args) {

new ChatClient("localhost", 12345); // Connect to server on localhost and port 12345

User Interface
The user interface of our chat application is designed to be simple, intuitive, and text-based, ensuring ease of

use for users of all levels. Users interact with the application through a console-based interface, where they

can input messages to send and receive messages from other connected users. The interface provides a clean

and minimalist design, focusing on functionality and efficiency.Upon launching the application, users are

greeted with a prompt to input their messages. Messages sent by the user are displayed in real-time, along

with incoming messages from other users. This real-time display ensures seamless communication and

fosters a sense of immediacy in conversations.A sample screenshot of the chat interface is provided below,

showcasing the simplicity and clarity of the user interface design.This user-friendly interface makes our chat
9|Page

application accessible to users across various platforms and devices, providing a seamless communication

experience.

Read me File
Simple Chat Application

This is a simple chat application implemented in Java, consisting of a server and client component. The

server allows multiple clients to connect simultaneously and exchange messages in a chat room-like

environment.

Features

Server:

Listens for incoming connections from clients.

Assigns a unique client ID to each connected client.

Broadcasts messages from one client to all other connected clients, allowing multiple users to chat with each

other.

Client:

Connects to the server using the server's IP address and port number.

Sends messages to the server.


10 | P a g e

Receives messages from the server and displays them in the console.

Usage

Server

Compile the ChatServer.java file: javac uoPeopleChatApplication/ChatServer.java

Run the compiled server class: java uoPeopleChatApplication.ChatServer

Client

Compile the ChatClient.java file: javac uoPeopleChatApplication/ChatClient.java

Run the compiled client class: java uoPeopleChatApplication.ChatClient <server_ip> <server_port>

Replace <server_ip> with the IP address of the server and <server_port> with the port number on which the

server is running (default port is 12345).

Enter messages in the client console to send them to the server and receive messages from other clients.

Important Notes

Make sure the server is running before clients attempt to connect.

Clients must know the IP address and port number of the server to connect successfully.

This application is intended for educational purposes and may not be suitable for production use without

further enhancements (e.g., security features, error handling).

Contributing
11 | P a g e

Contributions are welcome! Feel free to submit issues or pull requests if you have any suggestions for

improvements or bug fixes.

In conclusion, developing a chat application provides a valuable hands-on experience in understanding

network programming concepts and client-server communication protocols. Throughout this project,

developers gain insights into socket programming, threading, and handling concurrent connections. By

building a simple chat application, developers learn how to manage multiple clients, assign unique

identifiers, and facilitate real-time communication over a network. Additionally, this project fosters

collaboration and problem-solving skills, as developers encounter challenges related to synchronization,

error handling, and scalability. Overall, creating a chat application offers a practical opportunity to apply

theoretical knowledge, hone programming skills, and appreciate the complexities involved in designing and

implementing networked systems. Moreover, it serves as a foundational step towards developing more

sophisticated communication platforms and reinforces the importance of clear documentation, testing, and

iterative development practices.


12 | P a g e

References
1. Mishra, T. (2019). Java Based Chat Server.

2. Maruyama, H. (2002). XML and Java: developing Web applications. Addison-Wesley Professional.

You might also like