-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHandler.java
106 lines (94 loc) · 2.57 KB
/
Handler.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
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Handler implements Runnable {
protected Socket socket;
public String logins;
Server obj;
public Handler (String login)
{
this.logins=login;
}
public Handler (Socket socket,String logins) {
this.socket = socket;
this.logins= logins;
}
protected DataInputStream dataIn;
protected DataOutputStream dataOut;
protected Thread listener;
public synchronized void start () {
if (listener == null) {
try {
dataIn = new DataInputStream
(new BufferedInputStream (socket.getInputStream ()));
dataOut = new DataOutputStream
(new BufferedOutputStream (socket.getOutputStream ()));
listener = new Thread (this);
listener.start ();
} catch (IOException ignored) {}
}
}
public synchronized void stop () {
if (listener != null) {
try {
if (listener != Thread.currentThread ())
listener.interrupt ();
listener = null;
dataOut.close ();
String msg= "\n" + InetAddress.getLocalHost() + "has logged off.\n";
broadcast(msg);
obj.output.append("\n" + InetAddress.getLocalHost() + " has logged off.\n");
} catch (IOException ignored) {
}
}
}
protected static Vector handlers = new Vector ();
public void run () {
try {
handlers.addElement (this);
while (!Thread.interrupted ()) {
String message1 = dataIn.readUTF ();
String message=message1;
broadcast (message);
}
} catch (EOFException ignored) {
} catch (IOException ex) {
if (listener == Thread.currentThread ())
ex.printStackTrace ();
} finally {
handlers.removeElement (this);
}
stop ();
}
protected void broadcast (String message) {
synchronized (handlers) {
Enumeration en = handlers.elements ();
while (en.hasMoreElements ()) {
Handler handler = (Handler) en.nextElement ();
try {
handler.dataOut.writeUTF (message);
handler.dataOut.flush ();
} catch (IOException ex) {
handler.stop ();
}
}
}
}
protected void broadcastNew (String message) {
synchronized (handlers) {
Enumeration en = handlers.elements ();
while (en.hasMoreElements ()) {
Handler handler = (Handler) en.nextElement ();
try {
handler.dataOut.writeUTF (message);
handler.dataOut.flush ();
} catch (IOException ex) {
handler.stop ();
}
}
}
}
}