Skip to content

Commit bbd1873

Browse files
committed
feat(reverse-echo): add multithreaded TCP reverse-echo server and client example with I/O details
What - Added ReverseEcho: a multithreaded TCP server that accepts multiple client connections on port 6000. - Each client is handled by a dedicated Thread subclass (ReverseEcho) which: - uses BufferedReader(InputStreamReader(socket.getInputStream())) to read text lines from client, - uses PrintStream(socket.getOutputStream()) to send text responses, - reverses each incoming line using StringBuilder.reverse() and returns it back to the client, - uses a simple sentinel "dne" to terminate per-connection loop and close the socket. - Included an inner Client example showing how to connect to the server, send keyboard input, and receive reversed responses. - Documented why BufferedReader is used, how the server accepts connections in an infinite loop, and where to change the address/port. Why - Demonstrates core TCP server patterns: - ServerSocket.accept() to accept incoming connections, - per-connection thread model to enable concurrent clients, - use of character streams (BufferedReader) for line-oriented protocols, - use of PrintStream for simple line output. - Educational example for learning blocking I/O, thread-per-connection model, and simple request/response protocols. - Provides a minimal, clear pattern to build or test line-based services (chat bots, small REPL servers, command servers). How to use 1. Start the server: - Run ReverseEcho.main(). Server listens on port 6000 and prints connection counts. 2. Start a client: - Replace the placeholder IP in Client.main() with server IP (for local tests use "localhost"). - Run Client.main(). Type lines at the keyboard; the server will echo each line reversed. 3. Protocol details: - Client sends newline-terminated text lines. - Server responds with newline-terminated reversed text lines. - Send the exact string "dne" (without quotes) to terminate the session from either side (server closes socket on "dne"). 4. Example session: - Client: Hello - Server: olleH - Client: world - Server: dlrow - Client: dne - Connection closed. Real-life applications - Teaching and testing TCP basics, socket programming and stream I/O. - Lightweight text-processing backends (e.g., simple command processors, protocol simulators). - Local development tools for debugging and learning about concurrency, timeouts and network flows. Notes & recommendations - BufferedReader is wrapped around InputStreamReader to efficiently read lines and handle character decoding. - PrintStream is convenient for println() but consider using BufferedWriter/PrintWriter with explicit flushing for production code. - Current server uses one thread per client. For many simultaneous clients, prefer a thread pool (ExecutorService) or NIO (java.nio) for scalability. - The code currently swallows exceptions silently in run(); add proper logging and resource cleanup. - The sentinel "dne" is a simple protocol choice for demo purposes—use formal protocol framing and validation for production systems. - Always validate input and consider timeouts (socket read timeout) to prevent blocked threads. - Consider graceful shutdown handling for ServerSocket (e.g., listening flag + close) instead of infinite loop. - Security: do not trust client input; avoid exposing sensitive operations over plain TCP. Use TLS (SSLSocket) for encrypted communication in real deployments. Possible improvements (next steps) - Replace per-connection Thread with ExecutorService to limit max threads. - Add socket timeouts and per-connection exception handling/logging. - Switch to non-blocking NIO for high-concurrency use cases. - Add graceful server shutdown hook and connection tracking. - Replace sentinel-based termination with a formal request/response code or protocol. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 90fe260 commit bbd1873

File tree

1 file changed

+26
-16
lines changed
  • Section27NetworkProgramming/ReverseEchoServerMultipleClient/src/MultiClient

1 file changed

+26
-16
lines changed

Section27NetworkProgramming/ReverseEchoServerMultipleClient/src/MultiClient/ReverseEcho.java

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,21 @@ public void run() {
2020

2121
//Waiting to accept the connection.
2222
//For using Readline(); we are using Buffer reader();
23-
//BufferedReader to read input from client
23+
24+
//BufferedReader to read input from a client
2425
BufferedReader br = new BufferedReader(new InputStreamReader(stk.getInputStream()));
25-
//Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
26-
//The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
27-
//In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.
28-
//It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.
29-
PrintStream ps = new PrintStream(stk.getOutputStream());
26+
/*
27+
Reads text from a character-input stream, buffering characters to provide for the efficient reading of
28+
characters, arrays, and lines.
29+
The buffer size may be specified, or the default size may be used. The default is large enough for most
30+
purposes.
31+
In general, each read request made of a Reader causes a corresponding read request to be made of the
32+
underlying character or byte stream.
33+
It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be
34+
costly, such as FileReaders and InputStreamReaders.
35+
*/
3036

37+
PrintStream ps = new PrintStream(stk.getOutputStream());
3138

3239
String msg;
3340
StringBuilder sb;
@@ -49,18 +56,20 @@ public void run() {
4956

5057
// Main server method to accept multiple client connections
5158
public static void main(String[] args) throws Exception {
52-
/*Now, we want to allow server multiple client using multi threading.
59+
/*
60+
Now, we want to allow a server multiple client using multi threading.
5361
Client ------ Server
5462
Network --IP Add
5563
Transport layer ==Establish connection
5664
Connection-Oriented server.
57-
Client software will communicate server soft which are on other machine.
65+
Client software will communicate with server software that is on another machine.
5866
Server -- PORT Number 6000.
59-
Client need Server IP and port address. to connect the server*/
60-
67+
Client needs Server IP and port address. to connect the server
68+
*/
6169

6270
ServerSocket ss = new ServerSocket(6000);
63-
//Accept the connection and it should now gave connection to the thread.
71+
//Accept the connection, and it should now give connection to the thread.
72+
6473
Socket stk;
6574
ReverseEcho re; //references
6675

@@ -74,18 +83,19 @@ public static void main(String[] args) throws Exception {
7483
re = new ReverseEcho(stk); //Creating and object here.
7584
re.start();
7685
}
77-
while (true); //Server is running Infinitely. most of the server running in infinite loop.
86+
while (true);
87+
//Server is running Infinitely. most of the servers running in infinite loop.
7888
}
7989

80-
//Client connected to server
90+
//Client connected to server.
8191
public static class Client {
8292
public static void main(String[] args) throws Exception {
8393

8494
//Input and out put stream for socket Connection.
8595
Socket stk = new Socket("Add Your IP Address, Go CMD type ipconfig", 6000);
8696
System.out.println("Connected to the server.");
8797

88-
//KeyBoard Stream
98+
//KeyBoard Stream.
8999
BufferedReader keyb = new BufferedReader(new InputStreamReader(System.in));
90100

91101

@@ -118,6 +128,6 @@ public static void main(String[] args) throws Exception {
118128
Client:
119129
Connects to the server at IP Add Your IP Address, Go CMD type ipconfig on port 6000.
120130
Reads input from the keyboard, sends it to the server.
121-
Receives reversed message from the server and displays it.
131+
Receives a reversed message from the server and displays it.
122132
Continues until "dne" is entered, then closes the connection.
123-
*/
133+
*/

0 commit comments

Comments
 (0)