-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEchoServer.java
82 lines (67 loc) · 2.43 KB
/
EchoServer.java
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
79
80
81
82
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* EchoServer is a simple server which accepts a connection and
* simply reads input and echos it back to the sender.
*
* Code provided to enable testing of (1) sending/receiving messages from
* the server, and (2) updating a sketch based on messages.
*
* @author Travis Peters, Dartmouth CS 10, Winter 2015;
*/
public class EchoServer {
private ServerSocket listen; // for accepting connections
public EchoServer(ServerSocket listen) {
this.listen = listen;
}
///////////////////////////////////////////////////////////////////////
private class EchoServerCommunicator extends Thread {
private Socket sock;
private BufferedReader in; // from client
private PrintWriter out; // to client
public EchoServerCommunicator(Socket sock) {
this.sock = sock;
}
public void run() {
try {
System.out.println("editor connected for testing...");
// Communication channel
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
// Echo loop
String line;
while ((line = in.readLine()) != null) {
System.out.println("received: " + line);
send(line);
}
// Clean up
out.close();
in.close();
sock.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void send(String msg) {
System.out.println("send: " + msg);
out.println(msg);
}
}
///////////////////////////////////////////////////////////////////////
public void getConnections() throws IOException {
while (true) {
EchoServerCommunicator comm = new EchoServerCommunicator(listen.accept());
comm.setDaemon(true);
comm.start();
}
}
public static void main(String[] args) throws Exception {
System.out.println("Starting up the EchoServer...");
new EchoServer(new ServerSocket(5151)).getConnections();
}
}