forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiSimpleServer.java
More file actions
78 lines (76 loc) · 2.05 KB
/
MultiSimpleServer.java
File metadata and controls
78 lines (76 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// network/MultiSimpleServer.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Uses threads to handle any number of clients
// {ValidateByHand}
import java.io.*;
import java.net.*;
import onjava.*;
class ServeOneSimple extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServeOneSimple(Socket s)
throws IOException {
socket = s;
in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable auto-flush:
out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
// If any of the above calls throw an exception,
// the caller is responsible for closing the
// socket. Otherwise the thread closes it.
start(); // Calls run()
}
@Override
public void run() {
try {
while (true) {
String str = in.readLine();
if(str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
System.out.println("closing...");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
socket.close();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
public class MultiSimpleServer {
static final int PORT = 8080;
public static void
main(String[] args) throws IOException {
new TimedAbort(5); // Terminate after 5 seconds
ServerSocket s = new ServerSocket(PORT);
System.out.println("Server Started");
try {
while(true) {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
new ServeOneSimple(socket);
} catch(IOException e) {
// If it fails, close the socket,
// otherwise the thread will close it:
socket.close();
}
}
} finally {
s.close();
}
}
}