forked from mthli/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEchoServer.java
More file actions
44 lines (39 loc) · 1.2 KB
/
EchoServer.java
File metadata and controls
44 lines (39 loc) · 1.2 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
package server;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This program implements a simple server that listens to port 8189 and echoes back all client
* input.
* @version 1.21 2012-05-19
* @author Cay Horstmann
*/
public class EchoServer
{
public static void main(String[] args) throws IOException
{
// establish server socket
try (ServerSocket s = new ServerSocket(8189))
{
// wait for client connection
try (Socket incoming = s.accept())
{
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
try (Scanner in = new Scanner(inStream))
{
PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);
out.println("Hello! Enter BYE to exit.");
// echo client input
boolean done = false;
while (!done && in.hasNextLine())
{
String line = in.nextLine();
out.println("Echo: " + line);
if (line.trim().equals("BYE")) done = true;
}
}
}
}
}
}