Skip to content

Commit 135456c

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 dbc71e5 commit 135456c

File tree

1 file changed

+30
-19
lines changed

1 file changed

+30
-19
lines changed

Section27NetworkProgramming/ReverseEchoServerMultipleClient/src/RevserseEcho.java

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,27 +10,35 @@ class ReverseEcho extends Thread {
1010
public ReverseEcho(Socket st) {
1111
stk = st;
1212
}
13-
1413
public void run() {
1514
try {
1615
System.out.println("Client Handler Started for: " + stk.getInetAddress());
1716

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

2835
String msg;
2936
StringBuilder sb;
37+
3038
//Reversing a string. Try with StringBuffer.
3139
do {
3240
msg = br.readLine();
33-
if (msg == null) break; // In case client disconnects unexpectedly
41+
if (msg == null) break; // In case a client disconnects unexpectedly
3442

3543
sb = new StringBuilder(msg);
3644
sb.reverse();
@@ -47,25 +55,28 @@ public void run() {
4755

4856
// Main server method to accept multiple client connections
4957
public static void main(String[] args) throws Exception {
50-
//Now, we want to allow server multiple client using multi threading.
51-
//Client ------ Server
52-
//Network --IP Add
53-
//Transport layer ==Establish connection
54-
//Connection-Oriented server.
55-
//Client software will communicate server soft which are on other machine.
56-
//Server -- PORT Number 3000.
57-
//Client need Server IP and port address. to connect the server
58+
/*
59+
Now, we want to allow a server multiple client using multi threading.
60+
Client ------ Server
61+
Network --IP Add
62+
Transport layer ==Establish connection
63+
Connection-Oriented server.
64+
Client software will communicate with server software that is on another machine.
65+
Server -- PORT Number 3000.
66+
Client needs Server IP and port address. to connect the server
67+
*/
5868

5969
ServerSocket ss = new ServerSocket(3000);
60-
//Accept the connection and it should now gave connection to the thread.
70+
//Accept the connection, and it should now give a connection to the thread.
6171
Socket stk;
6272
ReverseEcho re; //references
6373

6474
int count = 1;
6575
System.out.println("Server started on port 3000. Waiting for clients...");
6676
do {
6777
stk = ss.accept();
68-
//Creating object of Reverse Echo class.
78+
//Creating an object of Reverse Echo class.
79+
6980
System.out.println("Client Connected: " + count++);
7081

7182
re = new ReverseEcho(stk); //Creating an object here.
@@ -111,6 +122,6 @@ public static void main(String[] args) throws Exception {
111122
Client:
112123
Connects to the server at IP localhost on port 3000.
113124
Reads input from the keyboard, sends it to the server.
114-
Receives reversed message from the server and displays it.
125+
Receives a reversed message from the server and displays it.
115126
Continues until "dne" is entered, then closes the connection.
116-
*/
127+
*/

0 commit comments

Comments
 (0)