package de.tutorials.training;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SocketExample {
public static void main(String[] args) {
/*
* Pseudo-Code
*
* [Server-Thread]
* server = new socketserver(4711)
*
* client = server.waitForClient()
*
* ...
* [Client-Thread]
*
* client = new socket("localhost",4711)
*
* a = console.readInt()
* client.writeInt(a)
*
* b=console.readInt()
* client.writeInt(b)
*
* ...
* [Server-Thread]
* a = server.readInt();
* b = server.readInt();
*
* c = a + b;
*
* server.writeInt(c);
*
* [Client-Thread]
*
* c = client.readInt();
*
* print "Ergebnis: " + c
*/
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new Server(4711));
executorService.execute(new Client("localhost",4711));
executorService.shutdownNow();
}
static class /* SingleThreaded */ Server implements Runnable {
private final int port;
public Server(int port) {
this.port = port;
}
@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println(getClass().getSimpleName() + " Warte auf Client-Verbindung...");
Socket socket = serverSocket.accept();
System.out.println(getClass().getSimpleName() + " Neue Client-Verbindung: " + socket);
try (DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
int a = in.readInt();
int b = in.readInt();
int c = a + b;
out.writeInt(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class Client implements Runnable {
private final String hostname;
private final int port;
public Client(String hostname, int port) {
this.port = port;
this.hostname = hostname;
}
@Override
public void run() {
try(Socket socket = new Socket(hostname,port)){
try (DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in)) {
System.out.print("Zahl 1: ");
int a = scanner.nextInt();
System.out.print("Zahl 2: ");
int b = scanner.nextInt();
out.writeInt(a);
out.writeInt(b);
int c = in.readInt();
System.out.println("Ergebnis: (" + a + "+" + b +") = " + c);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}