-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathThreadedEchoServer.java
More file actions
89 lines (80 loc) · 1.99 KB
/
Copy pathThreadedEchoServer.java
File metadata and controls
89 lines (80 loc) · 1.99 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
79
80
81
82
83
84
85
86
87
88
89
package threaded;
import java.io.*;
import java.net.*;
import java.util.*;
/**
This program implements a multithreaded server that listens to port 8189 and echoes back
all client input.
@author Cay Horstmann
@version 1.21 2012-06-04
*/
public class ThreadedEchoServer
{
public static void main(String[] args )
{
try
{
int i = 1;
ServerSocket s = new ServerSocket(8189);
while (true)
{
Socket incoming = s.accept();
System.out.println("Spawning " + i);
Runnable r = new ThreadedEchoHandler(incoming);
Thread t = new Thread(r);
t.start();
i++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
This class handles the client input for one server socket connection.
*/
class ThreadedEchoHandler implements Runnable
{
private Socket incoming;
/**
Constructs a handler.
@param i the incoming socket
*/
public ThreadedEchoHandler(Socket i)
{
incoming = i;
}
public void run()
{
try
{
try
{
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
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;
}
}
finally
{
incoming.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}