OnJava8-Examples/network/MultiServer.java

61 lines
1.7 KiB
Java
Raw Normal View History

// network/MultiServer.java
2015-12-15 11:47:04 -08:00
// (c)2016 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.
2016-09-03 12:18:15 -06:00
// Uses threads to handle any number of clients.
package network;
2015-06-15 17:47:35 -07:00
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
2015-06-15 17:47:35 -07:00
class ServeOne implements Runnable {
2016-09-03 12:18:15 -06:00
private ServerSocket ss;
static final int PORT = 8080;
public ServeOne(ServerSocket ss) throws IOException {
2016-09-03 12:18:15 -06:00
this.ss = ss;
2015-06-15 17:47:35 -07:00
}
@Override
public void run() {
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 -> {
if (message.equals("END")) {
System.out.println("Received END. Closing Socket.");
return true;
}
System.out.println("Message : " + message);
out.println(message);
return false;
});
2015-06-15 17:47:35 -07: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 {
private ExecutorService pool;
public void run() {
pool = Executors.newFixedThreadPool(30);
try (ServerSocket ss = new ServerSocket(ServeOne.PORT)) {
while (true) {
pool.submit(new ServeOne(ss));
2015-06-15 17:47:35 -07:00
}
} catch (IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
}
2015-09-07 11:44:36 -06:00
}