0% found this document useful (0 votes)
60 views6 pages

Chat Application Setup in Jvdroid

Uploaded by

madandolataiwo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views6 pages

Chat Application Setup in Jvdroid

Uploaded by

madandolataiwo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Note: this is written to run in Jvdroid

Import [Link].*;
Import [Link].*;
Import [Link].*;

Public class ChatApp {


Private static Set<ClientHandler> clientHandlers = new HashSet<>();
Private static int userId = 0;
Private static final int PORT = 12345;

Public static void main(String[] args) {


// Start the server in a new thread
New Thread(() -> {
Try (ServerSocket serverSocket = new ServerSocket(PORT)) {
[Link](“Chat server started…”);

While (true) {
Socket clientSocket = [Link]();
userId++;
ClientHandler clientHandler = new ClientHandler(clientSocket, userId);
[Link](clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
[Link](“Error starting server: “ + [Link]());
}
}).start();

// Run the client side


Try (Socket socket = new Socket(“localhost”, PORT);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader userInput = new BufferedReader(new InputStreamReader([Link])))
{

[Link](“Connected to the chat server”);

// Create a thread to listen for incoming messages


New Thread(() -> {
Try {
String message;
While ((message = [Link]()) != null) {
[Link](message);
}
} catch (IOException e) {
[Link](“Error reading messages: “ + [Link]());
}
}).start();

String userMessage;
While ((userMessage = [Link]()) != null) {
[Link](userMessage);
}
} catch (IOException e) {
[Link](“Error connecting to server: “ + [Link]());
}
}

// Handles each connected client


Static class ClientHandler implements Runnable {
Private Socket socket;
Private PrintWriter out;
Private BufferedReader in;
Private int userId;

Public ClientHandler(Socket socket, int userId) {


[Link] = socket;
[Link] = userId;
}

@Override
Public void run() {
Try {
Out = new PrintWriter([Link](), true);
In = new BufferedReader(new InputStreamReader([Link]()));
String message;

[Link](“User” + userId + “ connected.”);

// Notify others about the new user


broadcastMessage(“User” + userId + “ has joined the chat.”, this);

while ((message = [Link]()) != null) {


[Link](“User” + userId + “: “ + message);
broadcastMessage(“User” + userId + “: “ + message, this);
}
} catch (IOException e) {
[Link](“Error handling user” + userId + “: “ + [Link]());
} finally {
Try {
[Link]();
} catch (IOException e) {
[Link](“Error closing socket: “ + [Link]());
}
removeClient(this);
broadcastMessage(“User” + userId + “ has left the chat.”, this);
}
}

Public void sendMessage(String message) {


[Link](message);
}
}

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


For (ClientHandler clientHandler : clientHandlers) {
If (clientHandler != sender) {
[Link](message);
}
}
}

Public static void removeClient(ClientHandler clientHandler) {


[Link](clientHandler);
}
}

Output:
Key Changes:

The server and client logic are now in a single ChatApp class.

The server runs in a separate thread to keep the main thread free to run the client.

The ClientHandler is a nested class inside the main ChatApp class.

How to Run in Jvdroid:

Open Jvdroid and paste the entire code into a new file.
Save the file with a name like [Link].
Compile and run the code. This should start the server, and the client will connect to the same
server immediately after.
Reference:
Bondar, S. (2023, April 18). Java file handling: Reading and writing text and binary files.
REINTECH. [Link]
Eck, D. J. (2022). Introduction to programming using java version 9, JavaFX edition. Licensed
under CC 4.0. [Link]
Pankaj. (2022, August 4). Java socket programming – Socket server, client example.
DigitalOcean. [Link]
server-client

Common questions

Powered by AI

The sender parameter in the broadcastMessage method is significant as it helps exclude the client who sent the message from the broadcast. This prevents the originating client from receiving its own message, which is often unnecessary and reduces redundant communication. It ensures efficient network use and a more intuitive user experience .

The ChatApp server handles concurrent client connections by spawning a new thread for each client that connects. When a client socket is accepted, a new ClientHandler instance is created to manage the client. A new thread is then started for this ClientHandler, allowing the server to listen for new connections while handling each client's communication independently .

The ChatApp ensures all connected clients receive messages by using a broadcastMessage method within the ChatApp class. When a client sends a message, this method iterates over all ClientHandler instances stored in a static Set, sending the message to each one except the sender. This ensures that messages are relayed to all clients in the chat environment .

Using a Set for clientHandlers enhances performance by maintaining a unique collection without duplicates, essential for managing distinct client connections in a chat system. Set operations like adding or removing client handlers have average time complexity of O(1), promoting efficient management of connections. This structure supports fast iteration for message broadcasting without redundant entries .

The ChatApp implements error handling using try-catch blocks surrounding critical operations like socket accepting and reading/writing streams. This approach helps capture exceptions like IOException to prevent crashes and display meaningful error messages. Additionally, finally blocks are used for cleanup operations, ensuring resources like sockets are closed properly, regardless of error conditions .

The static variable userId in ChatApp serves to uniquely identify each client connection by incrementing with each new socket connection. Meanwhile, clientHandlers, a static Set, stores all active ClientHandler instances, facilitating the broadcastMessage method's ability to communicate with all clients. These static variables ensure shared resources are accessible across threads and maintain consistent state tracking .

Running the server and client logic in a single class, ChatApp, brings simplicity to the application structure by housing all related functionalities in one location. This design eases management and development as there is no need to maintain multiple classes for basic chat functionality. It provides an integrated environment where server operations begin immediately after client setups, promoting seamless client-server interactions without additional configuration .

Java is a suitable choice for implementing a chat server and client due to its platform independence, robust standard library, and strong support for networking via socket programming. Java provides built-in classes like ServerSocket and Socket that simplify network communication. Its concurrency model, based on threads, supports handling multiple clients efficiently. Moreover, Java's exception handling mechanisms and portability make it ideal for building reliable and maintainable chat applications .

Client disconnections are handled through a finally block in the ClientHandler's run method. If a client's communication is interrupted, the finally block ensures the socket is closed and the client is removed from the clientHandlers Set using removeClient. This cleanup prevents resource leaks and notifies other users that a client has left the chat, maintaining the chat's integrity .

The ClientHandler class is a nested class within ChatApp, designed to manage individual client connections. Each ClientHandler maintains a unique connection with its client by managing the input and output streams. It processes incoming messages and invokes broadcastMessage to share these messages with other clients. By isolating client-specific handling in ClientHandler, the app separates connection management from the main server logic .

You might also like