Skip to content

Commit 5c1eac1

Browse files
committed
Add Java network programming (part II) code snippets
1 parent 3dabb1a commit 5c1eac1

17 files changed

Lines changed: 935 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package bg.sofia.uni.fmi.mjt.echo.net.multithreaded;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
import java.net.Socket;
8+
9+
public class ClientRequestHandler implements Runnable {
10+
11+
private Socket socket;
12+
13+
public ClientRequestHandler(Socket socket) {
14+
this.socket = socket;
15+
}
16+
17+
@Override
18+
public void run() {
19+
20+
Thread.currentThread().setName("Client Request Handler for " + socket.getRemoteSocketAddress());
21+
22+
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // autoflush on
23+
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
24+
25+
String inputLine;
26+
while ((inputLine = in.readLine()) != null) { // read the message from the client
27+
System.out.println("Message received from client: " + inputLine);
28+
out.println("Echo " + inputLine); // send response back to the client
29+
}
30+
31+
} catch (IOException e) {
32+
System.out.println(e.getMessage());
33+
} finally {
34+
try {
35+
socket.close();
36+
} catch (IOException e) {
37+
e.printStackTrace();
38+
}
39+
}
40+
41+
}
42+
43+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package bg.sofia.uni.fmi.mjt.echo.net.multithreaded;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
import java.net.Socket;
8+
import java.util.Scanner;
9+
10+
public class EchoClient {
11+
12+
private static final int SERVER_PORT = 4444;
13+
14+
public static void main() {
15+
16+
try (Socket socket = new Socket("localhost", SERVER_PORT);
17+
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on
18+
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
19+
Scanner scanner = new Scanner(System.in)) {
20+
21+
Thread.currentThread().setName("Echo client thread " + socket.getLocalPort());
22+
23+
System.out.println("Connected to the server.");
24+
25+
while (true) {
26+
System.out.print("Enter message: ");
27+
String message = scanner.nextLine(); // read a line from the console
28+
29+
if ("quit".equals(message)) {
30+
break;
31+
}
32+
33+
System.out.println("Sending message <" + message + "> to the server...");
34+
35+
writer.println(message); // send the message to the server
36+
37+
String reply = reader.readLine(); // read the response from the server
38+
System.out.println("The server replied <" + reply + ">");
39+
}
40+
41+
} catch (IOException e) {
42+
throw new RuntimeException("There is a problem with the network communication", e);
43+
}
44+
}
45+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package bg.sofia.uni.fmi.mjt.echo.net.multithreaded;
2+
3+
import java.io.IOException;
4+
import java.net.ServerSocket;
5+
import java.net.Socket;
6+
import java.util.concurrent.ExecutorService;
7+
import java.util.concurrent.Executors;
8+
9+
public class EchoServer {
10+
11+
private static final int SERVER_PORT = 4444;
12+
private static final int MAX_EXECUTOR_THREADS = 10;
13+
14+
static void main() {
15+
Thread.currentThread().setName("Echo Server Thread");
16+
17+
try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
18+
ExecutorService executor = Executors.newFixedThreadPool(MAX_EXECUTOR_THREADS);) {
19+
20+
System.out.println("Server started and listening for connect requests");
21+
Socket clientSocket;
22+
23+
while (true) {
24+
// Calling accept() blocks and waits for connection request by a client
25+
// When a request comes, accept() returns a socket to communicate with this
26+
// client
27+
clientSocket = serverSocket.accept();
28+
29+
System.out.println("Accepted connection request from client " + clientSocket.getInetAddress() + ":" +
30+
clientSocket.getPort());
31+
32+
// We want each client to be processed in a separate thread
33+
// to keep the current thread free to accept() requests from new clients
34+
ClientRequestHandler clientHandler = new ClientRequestHandler(clientSocket);
35+
36+
// uncomment the line below to launch a thread manually
37+
// new Thread(clientHandler).start();
38+
executor.execute(clientHandler); // use a thread pool to launch a thread
39+
}
40+
} catch (IOException e) {
41+
throw new RuntimeException("There is a problem with the server socket", e);
42+
}
43+
}
44+
45+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package bg.sofia.uni.fmi.mjt.echo.net.simple;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
import java.net.Socket;
8+
import java.util.Scanner;
9+
10+
public class EchoClient {
11+
12+
private static final int SERVER_PORT = 6666;
13+
14+
static void main() {
15+
16+
try (Socket socket = new Socket("localhost", SERVER_PORT);
17+
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on
18+
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
19+
Scanner scanner = new Scanner(System.in)) {
20+
21+
System.out.println("Connected to the server.");
22+
23+
while (true) {
24+
System.out.print("Enter message: ");
25+
String message = scanner.nextLine(); // read a line from the console
26+
27+
if ("quit".equals(message)) {
28+
break;
29+
}
30+
31+
System.out.println("Sending message <" + message + "> to the server...");
32+
33+
writer.println(message); // send the message to the server
34+
35+
String reply = reader.readLine(); // read the response from the server
36+
System.out.println("The server replied <" + reply + ">");
37+
}
38+
39+
} catch (IOException e) {
40+
throw new RuntimeException("There is a problem with the network communication", e);
41+
}
42+
43+
}
44+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package bg.sofia.uni.fmi.mjt.echo.net.simple;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
import java.net.ServerSocket;
8+
import java.net.Socket;
9+
10+
public class EchoServer {
11+
12+
private static final int SERVER_PORT = 6666;
13+
14+
static void main() {
15+
16+
try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) {
17+
System.out.println("Server started and listening for connect request");
18+
19+
try (Socket clientSocket = serverSocket.accept();
20+
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
21+
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { // autoflush on
22+
23+
String inputLine;
24+
while ((inputLine = br.readLine()) != null) {
25+
System.out.println("Message received from client: " + inputLine);
26+
out.println("Echo " + inputLine);
27+
}
28+
}
29+
30+
} catch (IOException e) {
31+
throw new RuntimeException("There is a problem with the server socket", e);
32+
}
33+
}
34+
35+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package bg.sofia.uni.fmi.mjt.echo.nio;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.PrintWriter;
6+
import java.net.InetSocketAddress;
7+
import java.nio.channels.Channels;
8+
import java.nio.channels.SocketChannel;
9+
import java.util.Scanner;
10+
11+
// NIO specifics wrapped & hidden
12+
public class EchoClient {
13+
14+
private static final int SERVER_PORT = 7777;
15+
16+
static void main() {
17+
18+
try (SocketChannel socketChannel = SocketChannel.open();
19+
BufferedReader reader = new BufferedReader(Channels.newReader(socketChannel, "UTF-8"));
20+
PrintWriter writer = new PrintWriter(Channels.newWriter(socketChannel, "UTF-8"), true);
21+
Scanner scanner = new Scanner(System.in)) {
22+
23+
socketChannel.connect(new InetSocketAddress("localhost", SERVER_PORT));
24+
25+
System.out.println("Connected to the server.");
26+
27+
while (true) {
28+
System.out.print("Enter message: ");
29+
String message = scanner.nextLine(); // read a line from the console
30+
31+
if ("quit".equals(message)) {
32+
break;
33+
}
34+
35+
System.out.println("Sending message <" + message + "> to the server...");
36+
37+
writer.println(message);
38+
39+
String reply = reader.readLine(); // read the response from the server
40+
System.out.println("The server replied <" + reply + ">");
41+
}
42+
} catch (IOException e) {
43+
throw new RuntimeException("There is a problem with the network communication", e);
44+
}
45+
}
46+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package bg.sofia.uni.fmi.mjt.echo.nio;
2+
3+
import java.io.IOException;
4+
import java.net.InetSocketAddress;
5+
import java.nio.ByteBuffer;
6+
import java.nio.channels.SocketChannel;
7+
import java.util.Scanner;
8+
9+
// NIO, blocking
10+
public class EchoClientNio {
11+
12+
private static final int SERVER_PORT = 7777;
13+
private static final String SERVER_HOST = "localhost";
14+
private static final int BUFFER_SIZE = 512;
15+
16+
private static ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
17+
18+
public static void main() {
19+
20+
try (SocketChannel socketChannel = SocketChannel.open();
21+
Scanner scanner = new Scanner(System.in)) {
22+
23+
socketChannel.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT));
24+
25+
System.out.println("Connected to the server.");
26+
27+
while (true) {
28+
System.out.print("Enter message: ");
29+
String message = scanner.nextLine(); // read a line from the console
30+
31+
if ("quit".equals(message)) {
32+
break;
33+
}
34+
35+
System.out.println("Sending message <" + message + "> to the server...");
36+
37+
buffer.clear(); // switch to writing mode
38+
buffer.put(message.getBytes()); // buffer fill
39+
buffer.flip(); // switch to reading mode
40+
socketChannel.write(buffer); // buffer drain
41+
42+
buffer.clear(); // switch to writing mode
43+
socketChannel.read(buffer); // buffer fill
44+
buffer.flip(); // switch to reading mode
45+
46+
byte[] byteArray = new byte[buffer.remaining()];
47+
buffer.get(byteArray);
48+
String reply = new String(byteArray, "UTF-8"); // buffer drain
49+
50+
// if the buffer is a non-direct one, it has a wrapped array and we can get it
51+
//String reply = new String(buffer.array(), 0, buffer.position(), "UTF-8"); // buffer drain
52+
53+
System.out.println("The server replied <" + reply + ">");
54+
}
55+
56+
} catch (IOException e) {
57+
throw new RuntimeException("There is a problem with the network communication", e);
58+
}
59+
}
60+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package bg.sofia.uni.fmi.mjt.echo.nio;
2+
3+
import java.io.IOException;
4+
import java.net.InetSocketAddress;
5+
import java.nio.ByteBuffer;
6+
import java.nio.channels.SelectionKey;
7+
import java.nio.channels.Selector;
8+
import java.nio.channels.ServerSocketChannel;
9+
import java.nio.channels.SocketChannel;
10+
import java.util.Iterator;
11+
import java.util.Set;
12+
13+
public class EchoServer {
14+
public static final int SERVER_PORT = 7777;
15+
private static final String SERVER_HOST = "localhost";
16+
private static final int BUFFER_SIZE = 1024;
17+
18+
public static void main() {
19+
try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
20+
21+
serverSocketChannel.bind(new InetSocketAddress(SERVER_HOST, SERVER_PORT));
22+
serverSocketChannel.configureBlocking(false);
23+
24+
Selector selector = Selector.open();
25+
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
26+
27+
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
28+
29+
while (true) {
30+
int readyChannels = selector.select();
31+
if (readyChannels == 0) {
32+
// select() is blocking but may still return with 0, check javadoc
33+
continue;
34+
}
35+
36+
Set<SelectionKey> selectedKeys = selector.selectedKeys();
37+
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
38+
39+
while (keyIterator.hasNext()) {
40+
SelectionKey key = keyIterator.next();
41+
if (key.isReadable()) {
42+
SocketChannel sc = (SocketChannel) key.channel();
43+
44+
buffer.clear();
45+
int r = sc.read(buffer);
46+
if (r < 0) {
47+
System.out.println("Client has closed the connection");
48+
sc.close();
49+
continue;
50+
}
51+
buffer.flip();
52+
sc.write(buffer);
53+
54+
} else if (key.isAcceptable()) {
55+
ServerSocketChannel sockChannel = (ServerSocketChannel) key.channel();
56+
SocketChannel accept = sockChannel.accept();
57+
accept.configureBlocking(false);
58+
accept.register(selector, SelectionKey.OP_READ);
59+
}
60+
61+
keyIterator.remove();
62+
}
63+
64+
}
65+
66+
} catch (IOException e) {
67+
throw new RuntimeException("There is a problem with the server socket", e);
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)