Skip to content

Commit 37d73a8

Browse files
Single Client Chat & Multiple Client Chat Connection
In Java, a single-client chat connection typically involves a server and one client, where the server waits for the client's messages and responds accordingly. This setup uses ServerSocket to listen for connections and Socket to handle communication. For multiple-client chat connections, the server needs to handle simultaneous interactions with multiple clients. This is achieved through multithreading, where each client connection is managed by a separate thread. The server continues to use ServerSocket to accept connections, while each client's communication is handled in an individual Thread using Socket. This approach ensures that the server can maintain concurrent conversations with multiple clients, enabling a robust and scalable chat application.
1 parent 068547f commit 37d73a8

20 files changed

+291
-0
lines changed

Client Connection/1.jpg

196 KB
Loading

Client Connection/2.jpg

172 KB
Loading

Client Connection/3.jpg

227 KB
Loading

Client Connection/4.jpg

179 KB
Loading

Client Connection/5.jpg

249 KB
Loading

Client Connection/6.jpg

210 KB
Loading

Client Connection/7.jpg

235 KB
Loading

Client/Client.class

2 KB
Binary file not shown.

Client/MultiClient.class

2.9 KB
Binary file not shown.

Client/MultiClient.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.io.*;
2+
import java.net.*;
3+
4+
public class MultiClient {
5+
private static final String SERVER_ADDRESS = "localhost"; // Change this to the server's IP address if it's not
6+
// localhost
7+
private static final int SERVER_PORT = 1234;
8+
9+
public static void main(String[] args) {
10+
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
11+
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
12+
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
13+
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) {
14+
15+
System.out.println("Connected to server: " + socket.getRemoteSocketAddress());
16+
17+
// Start a new thread to continuously read messages from the server
18+
new Thread(() -> {
19+
try {
20+
String serverResponse;
21+
while ((serverResponse = reader.readLine()) != null) {
22+
System.out.println(serverResponse); // Display server messages
23+
}
24+
} catch (IOException e) {
25+
e.printStackTrace();
26+
}
27+
}).start();
28+
29+
// Read user input and send it to the server
30+
String userInputLine;
31+
while ((userInputLine = userInput.readLine()) != null) {
32+
writer.println(userInputLine); // Send user input to server
33+
// Break the loop if the user types "/exit"
34+
if (userInputLine.trim().equalsIgnoreCase("/exit")) {
35+
break;
36+
}
37+
}
38+
} catch (IOException e) {
39+
e.printStackTrace();
40+
}
41+
}
42+
}

Client/SingleClient.class

2.9 KB
Binary file not shown.

Client/SingleClient.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.io.*;
2+
import java.net.*;
3+
4+
public class SingleClient {
5+
private static final String SERVER_ADDRESS = "localhost"; // Change this to the server's IP address if it's not
6+
// localhost
7+
private static final int SERVER_PORT = 1234;
8+
9+
public static void main(String[] args) {
10+
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
11+
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
12+
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
13+
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) {
14+
15+
System.out.println("Connected to server: " + socket.getRemoteSocketAddress());
16+
17+
// Start a new thread to continuously read messages from the server
18+
new Thread(() -> {
19+
try {
20+
String serverResponse;
21+
while ((serverResponse = reader.readLine()) != null) {
22+
System.out.println(serverResponse); // Display server messages
23+
}
24+
} catch (IOException e) {
25+
e.printStackTrace();
26+
}
27+
}).start();
28+
29+
// Read user input and send it to the server
30+
String userInputLine;
31+
while ((userInputLine = userInput.readLine()) != null) {
32+
writer.println(userInputLine); // Send user input to server
33+
// Break the loop if the user types "/exit"
34+
if (userInputLine.trim().equalsIgnoreCase("/exit")) {
35+
break;
36+
}
37+
}
38+
} catch (IOException e) {
39+
e.printStackTrace();
40+
}
41+
}
42+
}

ClientThread.class

2.16 KB
Binary file not shown.

ClientThread.java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Save this as Server/ClientThread.java
2+
import java.io.*;
3+
import java.net.*;
4+
5+
public class ClientThread implements Runnable {
6+
private Socket socket;
7+
private Server server;
8+
private String clientName;
9+
10+
public ClientThread(Server server, Socket socket) {
11+
this.server = server;
12+
this.socket = socket;
13+
}
14+
15+
public String getClientName() {
16+
return clientName;
17+
}
18+
19+
public void setClientName(String clientName) {
20+
this.clientName = clientName;
21+
}
22+
23+
public Socket getSocket() {
24+
return socket;
25+
}
26+
27+
public void setSocket(Socket socket) {
28+
this.socket = socket;
29+
}
30+
31+
@Override
32+
public void run() {
33+
try {
34+
DataInputStream in = new DataInputStream(socket.getInputStream());
35+
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
36+
37+
out.writeUTF("HI FROM SERVER");
38+
while (!socket.isClosed()) {
39+
try {
40+
if (in.available() > 0) {
41+
String input = in.readUTF();
42+
for (ClientThread thatClient : server.getClients()) {
43+
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
44+
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
45+
}
46+
}
47+
} catch (IOException e) {
48+
e.printStackTrace();
49+
}
50+
}
51+
} catch (IOException e) {
52+
e.printStackTrace();
53+
}
54+
}
55+
}

MultiClientServer$ClientHandler.class

2.38 KB
Binary file not shown.

MultiClientServer.class

3.3 KB
Binary file not shown.

MultiClientServer.java

+109
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import java.io.*;
2+
import java.net.*;
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
6+
public class MultiClientServer {
7+
private static final int PORT = 1234;
8+
private static volatile boolean running = true;
9+
private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
10+
private static ServerSocket serverSocket;
11+
12+
public static void main(String[] args) {
13+
// Start a thread to listen for shutdown commands
14+
new Thread(() -> {
15+
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
16+
try {
17+
while (running) {
18+
String command = consoleReader.readLine();
19+
if (command.equalsIgnoreCase("shutdown")) {
20+
running = false;
21+
System.out.println("Server is shutting down...");
22+
if (serverSocket != null && !serverSocket.isClosed()) {
23+
serverSocket.close();
24+
}
25+
threadPool.shutdown();
26+
}
27+
}
28+
} catch (IOException e) {
29+
e.printStackTrace();
30+
}
31+
}).start();
32+
33+
try {
34+
serverSocket = new ServerSocket(PORT);
35+
System.out.println("Server is listening on port " + PORT);
36+
37+
// Main loop to accept client connections
38+
while (running) {
39+
try {
40+
Socket clientSocket = serverSocket.accept();
41+
System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress());
42+
43+
// Handle client communication in a new thread
44+
threadPool.execute(new ClientHandler(clientSocket));
45+
} catch (IOException e) {
46+
if (!running) {
47+
System.out.println("Server has been shut down.");
48+
} else {
49+
e.printStackTrace();
50+
}
51+
}
52+
}
53+
} catch (IOException e) {
54+
if (!running) {
55+
System.out.println("Server has been shut down.");
56+
} else {
57+
e.printStackTrace();
58+
}
59+
} finally {
60+
if (serverSocket != null && !serverSocket.isClosed()) {
61+
try {
62+
serverSocket.close();
63+
} catch (IOException e) {
64+
e.printStackTrace();
65+
}
66+
}
67+
threadPool.shutdown();
68+
}
69+
}
70+
71+
private static class ClientHandler implements Runnable {
72+
private Socket clientSocket;
73+
74+
public ClientHandler(Socket clientSocket) {
75+
this.clientSocket = clientSocket;
76+
}
77+
78+
@Override
79+
public void run() {
80+
try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
81+
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)) {
82+
83+
String inputLine;
84+
while ((inputLine = reader.readLine()) != null) {
85+
System.out.println("Received from client: " + inputLine);
86+
87+
if (inputLine.trim().equalsIgnoreCase("/exit")) {
88+
writer.println("Server: Closing connection...");
89+
break;
90+
}
91+
92+
writer.println("Server: " + inputLine);
93+
}
94+
95+
System.out.println("Connection closed");
96+
} catch (IOException e) {
97+
e.printStackTrace();
98+
} finally {
99+
try {
100+
if (clientSocket != null && !clientSocket.isClosed()) {
101+
clientSocket.close();
102+
}
103+
} catch (IOException e) {
104+
e.printStackTrace();
105+
}
106+
}
107+
}
108+
}
109+
}

Server.class

2.8 KB
Binary file not shown.

SingleClientServer.class

2.29 KB
Binary file not shown.

SingleClientServer.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.io.*;
2+
import java.net.*;
3+
4+
public class SingleClientServer {
5+
private static final int PORT = 1234;
6+
7+
public static void main(String[] args) {
8+
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
9+
System.out.println("Server is listening on port " + PORT);
10+
11+
// Wait for a client to connect
12+
Socket clientSocket = serverSocket.accept();
13+
System.out.println("Client connected: " + clientSocket.getRemoteSocketAddress());
14+
15+
// Set up input and output streams
16+
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
17+
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
18+
19+
String inputLine;
20+
while ((inputLine = reader.readLine()) != null) {
21+
// Process input from client
22+
System.out.println("Received from client: " + inputLine);
23+
24+
// Check if the received message is the exit command
25+
if (inputLine.trim().equalsIgnoreCase("/exit")) {
26+
writer.println("Server: Closing connection..."); // Send a confirmation message to the client
27+
break; // Exit the loop to close the connection with the client
28+
}
29+
30+
// Echo back to client
31+
writer.println("Server: " + inputLine);
32+
}
33+
34+
// Close streams and socket
35+
reader.close();
36+
writer.close();
37+
clientSocket.close();
38+
System.out.println("Connection closed");
39+
} catch (IOException e) {
40+
e.printStackTrace();
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)