-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEchoThread.java
111 lines (81 loc) · 2.88 KB
/
EchoThread.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package myClient;
import java.lang.Thread; // We will extend Java's base Thread class
import java.io.ObjectInputStream; // For reading Java objects off of the wire
import java.io.ObjectOutputStream; // For writing Java objects to the wire
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLSocket;
/**
* A simple server thread. This class just echoes the messages sent
* over the socket until the socket is closed.
*
*/
public class EchoThread extends Thread
{
private ObjectOutputStream clientOut;
private EchoServer server;
private SSLSocket socket; // The socket that we'll be talking over
final static Charset ENCODING = StandardCharsets.UTF_8;
/**
* Constructor that sets up the socket we'll chat over
*
* @param _socket The socket passed in from the server
*
*/
public EchoThread(EchoServer server, SSLSocket _socket)
{
this.server = server;
socket = _socket;
}
private ObjectOutputStream getClientOut() {return clientOut;}
public void run()
{
//socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
try{
//setup i/o
this.clientOut = new ObjectOutputStream(socket.getOutputStream());
final ObjectInputStream objInput = new ObjectInputStream(socket.getInputStream());
Message input = null;
while(!socket.isClosed()) {
try {
input = (Message) objInput.readObject();
// NOTE: if you want to check server can read input,
//uncomment next line and check server file console.
//System.out.println(input);
for (EchoThread thatClient : server.getClients()) {
ObjectOutputStream thatClientOut = thatClient.getClientOut();
if (thatClientOut != null) {
thatClientOut.writeObject(input);
thatClientOut.flush();
}
}
} catch (IOException eof){
System.err.println(eof.getMessage());
System.out.println("client connection shutdown");
socket.close();
System.out.println("after socket.close");
objInput.close();
System.out.println("after objInput.close");
clientOut.close();
System.out.println("after clientOut.close");
} catch (Exception e) {
e.printStackTrace();
}
} //end while
try {
server.removeClient(this);
System.out.println("join EchoThread");
join();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
} catch (IOException io) {
System.err.println("Error: " + io.getMessage());
io.printStackTrace();
} catch(Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
} //-- end run()
} //-- end class EchoThread