OnJava8-Examples/network/MultiServer.java

64 lines
1.6 KiB
Java
Raw Normal View History

// network/MultiServer.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2017-01-22 16:48:11 -08:00
// Uses concurrency to handle any number of clients.
2015-06-15 17:47:35 -07:00
import java.io.*;
import java.net.*;
2017-01-22 16:48:11 -08:00
import java.util.concurrent.*;
2015-06-15 17:47:35 -07:00
class ServeOne implements Runnable {
static final int PORT = 8080;
2017-01-22 16:48:11 -08:00
private ServerSocket ss;
public ServeOne(ServerSocket ss) {
2016-09-03 12:18:15 -06:00
this.ss = ss;
2015-06-15 17:47:35 -07:00
}
@Override
public void run() {
2017-01-22 16:48:11 -08:00
System.out.println("Starting ServeOne");
2016-09-03 12:18:15 -06:00
try (
Socket socket = ss.accept();
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
// Boolean enables auto-flush
2016-09-03 12:18:15 -06:00
socket.getOutputStream())), true)
) {
in.lines().anyMatch(message -> {
2017-01-22 16:48:11 -08:00
if(message.equals("END")) {
System.out.println(
"Received END. Closing Socket.");
return true;
}
2017-01-22 16:48:11 -08:00
System.out.println(
"Message : " + message);
out.println(message);
return false;
});
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
2016-08-31 12:30:03 -06:00
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
}
}
public class MultiServer implements Runnable {
2017-01-22 16:48:11 -08:00
@Override
public void run() {
2017-01-22 16:48:11 -08:00
System.out.println("Running MultiServer");
try (
ServerSocket ss =
new ServerSocket(ServeOne.PORT)
) {
while(true)
CompletableFuture.runAsync(new ServeOne(ss));
} catch(IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
}
2015-09-07 11:44:36 -06:00
}