Skip to content

Commit 3b431bd

Browse files
committed
Enhance Java Network Programming code snippets
1 parent f49ad63 commit 3b431bd

File tree

6 files changed

+27
-22
lines changed

6 files changed

+27
-22
lines changed

11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/multithreaded/ClientRequestHandler.java

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
public class ClientRequestHandler implements Runnable {
1010

11-
private Socket socket;
11+
private final Socket socket;
1212

1313
public ClientRequestHandler(Socket socket) {
1414
this.socket = socket;
@@ -20,7 +20,8 @@ public void run() {
2020
Thread.currentThread().setName("Client Request Handler for " + socket.getRemoteSocketAddress());
2121

2222
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // autoflush on
23-
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
23+
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
24+
socket) { // resources created elsewhere can also be declared here and will be auto-closed
2425

2526
String inputLine;
2627
while ((inputLine = in.readLine()) != null) { // read the message from the client
@@ -30,12 +31,6 @@ public void run() {
3031

3132
} catch (IOException e) {
3233
System.out.println(e.getMessage());
33-
} finally {
34-
try {
35-
socket.close();
36-
} catch (IOException e) {
37-
e.printStackTrace();
38-
}
3934
}
4035

4136
}

11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/multithreaded/EchoServer.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,16 @@ public class EchoServer {
1111

1212
private static final int SERVER_PORT = 4444;
1313
private static final int MAX_EXECUTOR_THREADS = 10;
14+
// In production, consider:
15+
// - Runtime.getRuntime().availableProcessors() for CPU-bound tasks
16+
// - Larger pool (e.g., availableProcessors() * 2-4) for I/O-bound tasks,
17+
// since threads block waiting for I/O and don't consume CPU
1418

1519
static void main() {
1620
Thread.currentThread().setName("Echo Server Thread");
1721

1822
try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
19-
ExecutorService executor = Executors.newFixedThreadPool(MAX_EXECUTOR_THREADS);) {
23+
ExecutorService executor = Executors.newFixedThreadPool(MAX_EXECUTOR_THREADS)) {
2024

2125
// Get the local IP address of the server
2226
InetAddress serverAddress = InetAddress.getLocalHost();

11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/simple/EchoClient.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,11 @@ public class EchoClient {
1313

1414
static void main() {
1515

16-
try (Socket socket = new Socket("192.168.0.3", SERVER_PORT);
16+
try (Socket socket = new Socket("localhost", SERVER_PORT);
1717
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on
1818
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
1919
Scanner scanner = new Scanner(System.in)) {
2020

21-
System.out.println("Connected to the server.");
22-
2321
while (true) {
2422
System.out.print("Enter message: ");
2523
String message = scanner.nextLine(); // read a line from the console
@@ -39,6 +37,6 @@ static void main() {
3937
} catch (IOException e) {
4038
throw new RuntimeException("There is a problem with the network communication", e);
4139
}
42-
40+
4341
}
4442
}

11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/simple/EchoServer.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,14 @@ static void main() {
2121
" and listening for connection requests on port " + SERVER_PORT);
2222

2323
try (Socket clientSocket = serverSocket.accept();
24-
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
24+
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
2525
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { // autoflush on
2626

2727
String inputLine;
28-
while ((inputLine = br.readLine()) != null) {
28+
while ((inputLine = in.readLine()) != null) {
2929
System.out.println("Message received from client: " + inputLine);
3030
out.println("Echo " + inputLine);
31+
//out.flush();
3132
}
3233
}
3334

11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/nio/EchoClientNio.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import java.net.InetSocketAddress;
55
import java.nio.ByteBuffer;
66
import java.nio.channels.SocketChannel;
7+
import java.nio.charset.StandardCharsets;
78
import java.util.Scanner;
89

910
// NIO, blocking
@@ -13,10 +14,10 @@ public class EchoClientNio {
1314
private static final String SERVER_HOST = "localhost";
1415
private static final int BUFFER_SIZE = 512;
1516

16-
private static ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
17-
1817
public static void main() {
1918

19+
ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
20+
2021
try (SocketChannel socketChannel = SocketChannel.open();
2122
Scanner scanner = new Scanner(System.in)) {
2223

@@ -35,7 +36,7 @@ public static void main() {
3536
System.out.println("Sending message <" + message + "> to the server...");
3637

3738
buffer.clear(); // switch to writing mode
38-
buffer.put(message.getBytes()); // buffer fill
39+
buffer.put(message.getBytes(StandardCharsets.UTF_8)); // buffer fill
3940
buffer.flip(); // switch to reading mode
4041
socketChannel.write(buffer); // buffer drain
4142

11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/nio/EchoServer.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@
1313

1414
public class EchoServer {
1515
public static final int SERVER_PORT = 7777;
16-
private static final String SERVER_HOST = "localhost";
16+
private static final String SERVER_HOST = "0.0.0.0";
17+
18+
// 0.0.0.0 is a special address meaning "listen on all network interfaces"
19+
// This allows clients to connect via localhost, your local IP address,
20+
// or any other IP address your machine has
21+
1722
private static final int BUFFER_SIZE = 1024;
1823

1924
public static void main() {
@@ -52,16 +57,17 @@ public static void main() {
5257
if (r < 0) {
5358
System.out.println("Client has closed the connection");
5459
sc.close();
60+
keyIterator.remove();
5561
continue;
5662
}
5763
buffer.flip();
5864
sc.write(buffer);
5965

6066
} else if (key.isAcceptable()) {
6167
ServerSocketChannel sockChannel = (ServerSocketChannel) key.channel();
62-
SocketChannel accept = sockChannel.accept();
63-
accept.configureBlocking(false);
64-
accept.register(selector, SelectionKey.OP_READ);
68+
SocketChannel remoteClientChannel = sockChannel.accept();
69+
remoteClientChannel.configureBlocking(false);
70+
remoteClientChannel.register(selector, SelectionKey.OP_READ);
6571
}
6672

6773
keyIterator.remove();

0 commit comments

Comments
 (0)