Repository navigation
Expand file tree
/
Copy pathConnection.java
More file actions
56 lines (47 loc) · 1.66 KB
/
Copy pathConnection.java
File metadata and controls
56 lines (47 loc) · 1.66 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
/******************************************************************************
* Compilation: javac Connection.java
*
******************************************************************************/
import java.net.Socket;
public class Connection extends Thread {
private Socket socket;
private Out out;
private In in;
private String message; // one line buffer
public Connection(Socket socket) {
in = new In(socket);
out = new Out(socket);
this.socket = socket;
}
public void println(String s) { out.println(s); }
public void run() {
String s;
while ((s = in.readLine()) != null) {
setMessage(s);
}
out.close();
in.close();
try { socket.close(); }
catch (Exception e) { e.printStackTrace(); }
System.err.println("closing socket");
}
/***************************************************************************
* The methods getMessage() and setMessage() are synchronized
* so that the thread in Connection doesn't call setMessage()
* while the ConnectionListener thread is calling getMessage().
***************************************************************************/
public synchronized String getMessage() {
if (message == null) return null;
String temp = message;
message = null;
notifyAll();
return temp;
}
public synchronized void setMessage(String s) {
if (message != null) {
try { wait(); }
catch (Exception ex) { ex.printStackTrace(); }
}
message = s;
}
}