-
Notifications
You must be signed in to change notification settings - Fork 137
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Java network programming code snippets
- Loading branch information
Showing
17 changed files
with
939 additions
and
0 deletions.
There are no files selected for viewing
43 changes: 43 additions & 0 deletions
43
...choclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/multithreaded/ClientRequestHandler.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.net.multithreaded; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.io.PrintWriter; | ||
import java.net.Socket; | ||
|
||
public class ClientRequestHandler implements Runnable { | ||
|
||
private Socket socket; | ||
|
||
public ClientRequestHandler(Socket socket) { | ||
this.socket = socket; | ||
} | ||
|
||
@Override | ||
public void run() { | ||
|
||
Thread.currentThread().setName("Client Request Handler for " + socket.getRemoteSocketAddress()); | ||
|
||
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // autoflush on | ||
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { | ||
|
||
String inputLine; | ||
while ((inputLine = in.readLine()) != null) { // read the message from the client | ||
System.out.println("Message received from client: " + inputLine); | ||
out.println("Echo " + inputLine); // send response back to the client | ||
} | ||
|
||
} catch (IOException e) { | ||
System.out.println(e.getMessage()); | ||
} finally { | ||
try { | ||
socket.close(); | ||
} catch (IOException e) { | ||
e.printStackTrace(); | ||
} | ||
} | ||
|
||
} | ||
|
||
} |
45 changes: 45 additions & 0 deletions
45
...snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/multithreaded/EchoClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.net.multithreaded; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.io.PrintWriter; | ||
import java.net.Socket; | ||
import java.util.Scanner; | ||
|
||
public class EchoClient { | ||
|
||
private static final int SERVER_PORT = 4444; | ||
|
||
public static void main(String[] args) { | ||
|
||
try (Socket socket = new Socket("localhost", SERVER_PORT); | ||
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on | ||
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); | ||
Scanner scanner = new Scanner(System.in)) { | ||
|
||
Thread.currentThread().setName("Echo client thread " + socket.getLocalPort()); | ||
|
||
System.out.println("Connected to the server."); | ||
|
||
while (true) { | ||
System.out.print("Enter message: "); | ||
String message = scanner.nextLine(); // read a line from the console | ||
|
||
if ("quit".equals(message)) { | ||
break; | ||
} | ||
|
||
System.out.println("Sending message <" + message + "> to the server..."); | ||
|
||
writer.println(message); // send the message to the server | ||
|
||
String reply = reader.readLine(); // read the response from the server | ||
System.out.println("The server replied <" + reply + ">"); | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the network communication", e); | ||
} | ||
} | ||
} |
49 changes: 49 additions & 0 deletions
49
...snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/multithreaded/EchoServer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.net.multithreaded; | ||
|
||
import java.io.IOException; | ||
import java.net.ServerSocket; | ||
import java.net.Socket; | ||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
|
||
public class EchoServer { | ||
|
||
private static final int SERVER_PORT = 4444; | ||
private static final int MAX_EXECUTOR_THREADS = 10; | ||
|
||
public static void main(String[] args) { | ||
|
||
ExecutorService executor = Executors.newFixedThreadPool(MAX_EXECUTOR_THREADS); | ||
|
||
Thread.currentThread().setName("Echo Server Thread"); | ||
|
||
try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) { | ||
|
||
System.out.println("Server started and listening for connect requests"); | ||
|
||
Socket clientSocket; | ||
|
||
while (true) { | ||
|
||
// Calling accept() blocks and waits for connection request by a client | ||
// When a request comes, accept() returns a socket to communicate with this | ||
// client | ||
clientSocket = serverSocket.accept(); | ||
|
||
System.out.println("Accepted connection request from client " + clientSocket.getInetAddress()); | ||
|
||
// We want each client to be processed in a separate thread | ||
// to keep the current thread free to accept() requests from new clients | ||
ClientRequestHandler clientHandler = new ClientRequestHandler(clientSocket); | ||
|
||
// uncomment the line below to launch a thread manually | ||
// new Thread(clientHandler).start(); | ||
executor.execute(clientHandler); // use a thread pool to launch a thread | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the server socket", e); | ||
} | ||
} | ||
|
||
} |
44 changes: 44 additions & 0 deletions
44
...ork-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/simple/EchoClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.net.simple; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.io.PrintWriter; | ||
import java.net.Socket; | ||
import java.util.Scanner; | ||
|
||
public class EchoClient { | ||
|
||
private static final int SERVER_PORT = 6666; | ||
|
||
public static void main(String[] args) { | ||
|
||
try (Socket socket = new Socket("localhost", SERVER_PORT); | ||
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // autoflush on | ||
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); | ||
Scanner scanner = new Scanner(System.in)) { | ||
|
||
System.out.println("Connected to the server."); | ||
|
||
while (true) { | ||
System.out.print("Enter message: "); | ||
String message = scanner.nextLine(); // read a line from the console | ||
|
||
if ("quit".equals(message)) { | ||
break; | ||
} | ||
|
||
System.out.println("Sending message <" + message + "> to the server..."); | ||
|
||
writer.println(message); // send the message to the server | ||
|
||
String reply = reader.readLine(); // read the response from the server | ||
System.out.println("The server replied <" + reply + ">"); | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the network communication", e); | ||
} | ||
|
||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
...ork-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/net/simple/EchoServer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.net.simple; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.io.PrintWriter; | ||
import java.net.ServerSocket; | ||
import java.net.Socket; | ||
|
||
public class EchoServer { | ||
|
||
private static final int SERVER_PORT = 6666; | ||
|
||
public static void main(String[] args) { | ||
|
||
try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT)) { | ||
System.out.println("Server started and listening for connect request"); | ||
|
||
try (Socket clientSocket = serverSocket.accept(); | ||
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | ||
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { // autoflush on | ||
|
||
String inputLine; | ||
while ((inputLine = br.readLine()) != null) { | ||
System.out.println("Message received from client: " + inputLine); | ||
out.println("Echo " + inputLine); | ||
} | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the server socket", e); | ||
} | ||
} | ||
|
||
} |
46 changes: 46 additions & 0 deletions
46
11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/nio/EchoClient.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.nio; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.PrintWriter; | ||
import java.net.InetSocketAddress; | ||
import java.nio.channels.Channels; | ||
import java.nio.channels.SocketChannel; | ||
import java.util.Scanner; | ||
|
||
// NIO specifics wrapped & hidden | ||
public class EchoClient { | ||
|
||
private static final int SERVER_PORT = 7777; | ||
|
||
public static void main(String[] args) { | ||
|
||
try (SocketChannel socketChannel = SocketChannel.open(); | ||
BufferedReader reader = new BufferedReader(Channels.newReader(socketChannel, "UTF-8")); | ||
PrintWriter writer = new PrintWriter(Channels.newWriter(socketChannel, "UTF-8"), true); | ||
Scanner scanner = new Scanner(System.in)) { | ||
|
||
socketChannel.connect(new InetSocketAddress("localhost", SERVER_PORT)); | ||
|
||
System.out.println("Connected to the server."); | ||
|
||
while (true) { | ||
System.out.print("Enter message: "); | ||
String message = scanner.nextLine(); // read a line from the console | ||
|
||
if ("quit".equals(message)) { | ||
break; | ||
} | ||
|
||
System.out.println("Sending message <" + message + "> to the server..."); | ||
|
||
writer.println(message); | ||
|
||
String reply = reader.readLine(); // read the response from the server | ||
System.out.println("The server replied <" + reply + ">"); | ||
} | ||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the network communication", e); | ||
} | ||
} | ||
} |
60 changes: 60 additions & 0 deletions
60
11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/nio/EchoClientNio.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.nio; | ||
|
||
import java.io.IOException; | ||
import java.net.InetSocketAddress; | ||
import java.nio.ByteBuffer; | ||
import java.nio.channels.SocketChannel; | ||
import java.util.Scanner; | ||
|
||
// NIO, blocking | ||
public class EchoClientNio { | ||
|
||
private static final int SERVER_PORT = 7777; | ||
private static final String SERVER_HOST = "localhost"; | ||
private static final int BUFFER_SIZE = 512; | ||
|
||
private static ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); | ||
|
||
public static void main(String[] args) { | ||
|
||
try (SocketChannel socketChannel = SocketChannel.open(); | ||
Scanner scanner = new Scanner(System.in)) { | ||
|
||
socketChannel.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT)); | ||
|
||
System.out.println("Connected to the server."); | ||
|
||
while (true) { | ||
System.out.print("Enter message: "); | ||
String message = scanner.nextLine(); // read a line from the console | ||
|
||
if ("quit".equals(message)) { | ||
break; | ||
} | ||
|
||
System.out.println("Sending message <" + message + "> to the server..."); | ||
|
||
buffer.clear(); // switch to writing mode | ||
buffer.put(message.getBytes()); // buffer fill | ||
buffer.flip(); // switch to reading mode | ||
socketChannel.write(buffer); // buffer drain | ||
|
||
buffer.clear(); // switch to writing mode | ||
socketChannel.read(buffer); // buffer fill | ||
buffer.flip(); // switch to reading mode | ||
|
||
byte[] byteArray = new byte[buffer.remaining()]; | ||
buffer.get(byteArray); | ||
String reply = new String(byteArray, "UTF-8"); // buffer drain | ||
|
||
// if the buffer is a non-direct one, it has a wrapped array and we can get it | ||
//String reply = new String(buffer.array(), 0, buffer.position(), "UTF-8"); // buffer drain | ||
|
||
System.out.println("The server replied <" + reply + ">"); | ||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the network communication", e); | ||
} | ||
} | ||
} |
70 changes: 70 additions & 0 deletions
70
11-network-ii/snippets/echoclientserver/src/bg/sofia/uni/fmi/mjt/echo/nio/EchoServer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package bg.sofia.uni.fmi.mjt.echo.nio; | ||
|
||
import java.io.IOException; | ||
import java.net.InetSocketAddress; | ||
import java.nio.ByteBuffer; | ||
import java.nio.channels.SelectionKey; | ||
import java.nio.channels.Selector; | ||
import java.nio.channels.ServerSocketChannel; | ||
import java.nio.channels.SocketChannel; | ||
import java.util.Iterator; | ||
import java.util.Set; | ||
|
||
public class EchoServer { | ||
public static final int SERVER_PORT = 7777; | ||
private static final String SERVER_HOST = "localhost"; | ||
private static final int BUFFER_SIZE = 1024; | ||
|
||
public static void main(String[] args) { | ||
try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) { | ||
|
||
serverSocketChannel.bind(new InetSocketAddress(SERVER_HOST, SERVER_PORT)); | ||
serverSocketChannel.configureBlocking(false); | ||
|
||
Selector selector = Selector.open(); | ||
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); | ||
|
||
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); | ||
|
||
while (true) { | ||
int readyChannels = selector.select(); | ||
if (readyChannels == 0) { | ||
// select() is blocking but may still return with 0, check javadoc | ||
continue; | ||
} | ||
|
||
Set<SelectionKey> selectedKeys = selector.selectedKeys(); | ||
Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); | ||
|
||
while (keyIterator.hasNext()) { | ||
SelectionKey key = keyIterator.next(); | ||
if (key.isReadable()) { | ||
SocketChannel sc = (SocketChannel) key.channel(); | ||
|
||
buffer.clear(); | ||
int r = sc.read(buffer); | ||
if (r < 0) { | ||
System.out.println("Client has closed the connection"); | ||
sc.close(); | ||
continue; | ||
} | ||
buffer.flip(); | ||
sc.write(buffer); | ||
|
||
} else if (key.isAcceptable()) { | ||
ServerSocketChannel sockChannel = (ServerSocketChannel) key.channel(); | ||
SocketChannel accept = sockChannel.accept(); | ||
accept.configureBlocking(false); | ||
accept.register(selector, SelectionKey.OP_READ); | ||
} | ||
|
||
keyIterator.remove(); | ||
} | ||
|
||
} | ||
|
||
} catch (IOException e) { | ||
throw new RuntimeException("There is a problem with the server socket", e); | ||
} | ||
} | ||
} |
Oops, something went wrong.