📄 chathandler.java
字号:
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatHandler extends Thread {
protected Socket s;
protected DataInputStream i;
protected DataOutputStream o;
Vector y = new Vector();
public ChatHandler (Socket s, Vector x) throws IOException {
this.s = s;
i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
y = x;
}
protected static Vector handlers = new Vector ();
public void run () {
String name = s.getInetAddress ().toString ();
String Listado="";
try {
for (int i=0; i < y.size() ; i++)
Listado=Listado+y.get(i)+"\n";
handlers.addElement (this);
broadcast ("->" + Listado);
while (true) {
String msg = i.readUTF ();
broadcast (name + " - " + msg);
}
} catch (IOException ex) {
ex.printStackTrace ();
} finally {
handlers.removeElement (this);
y.remove(name);
Listado="";
for (int i=0; i < y.size() ; i++)
Listado=Listado+y.get(i)+"\n";
broadcast ("<-" + Listado);
try {
s.close ();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
protected static void broadcast (String message) {
synchronized (handlers) {
Enumeration e = handlers.elements ();
while (e.hasMoreElements ()) {
ChatHandler c = (ChatHandler) e.nextElement ();
try {
synchronized (c.o) {
c.o.writeUTF (message);
}
c.o.flush ();
} catch (IOException ex) {
c.stop ();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -