//ChatServer
import java
import
import java
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer()
}
public void start() {
try {
ss = new ServerSocket(
started = true;
} catch (BindException e) {
System
System
System
} catch (IOException e) {
e
}
try {
while(started) {
Socket s = ss
Client c = new Client(s);
System
new Thread(c)
clients
//dis
}
} catch (IOException e) {
e
} finally {
try {
ss
} catch (IOException e) {
// TODO Auto
e
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this
try {
dis = new DataInputStream(s
dos = new DataOutputStream(s
bConnected = true;
} catch (IOException e) {
e
}
}
public void send(String str) {
try {
dos
} catch (IOException e) {
clients
System
//e
}
}
public void run() {
try {
while(bConnected) {
String str = dis
System
for(int i=
Client c = clients
c
//System
}
/*
for(Iterator<Client> it = erator(); it
Client c = it
c
}
*/
/*
Iterator<Client> it = erator();
while(it
Client c = it
c
}
*/
}
} catch (EOFException e) {
System
} catch (IOException e) {
e
} finally {
try {
if(dis != null) dis
if(dos != null) dos
if(s != null) {
s
//s = null;
}
} catch (IOException e
e
}
}
}
}
}
//ChatClient
import java
import java
import java
import
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient()
}
public void launchFrame() {
setLocation(
this
add(tfTxt
add(taContent
pack();
this
@Override
public void windowClosing(WindowEvent arg
disconnect();
System
}
});
tfTxt
setVisible(true);
connect();
tRecv
}
public void connect() {
try {
s = new Socket(
dos = new DataOutputStream(s
dis = new DataInputStream(s
System
bConnected = true;
} catch (UnknownHostException e) {
e
} catch (IOException e) {
e
}
}
public void disconnect() {
try {
dos
dis
s
} catch (IOException e) {
e
}
/*
try {
bConnected = false;
tRecv
} catch(InterruptedException e) {
e
} finally {
try {
dos
dis
s
} catch (IOException e) {
e
}
}
*/
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt
//taContent
tfTxt
try {
//System
dos
dos
//dos
} catch (IOException e
e
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dis
//System
taContent
}
} catch (SocketException e) {
System
} catch (EOFException e) {
System
} catch (IOException e) {
e
}
}
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25933.html