package text;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bconnection = false;
private static final long serialVersionUID = 1L;
TextField tf = new TextField();
TextArea ta = new TextArea();
Thread trece = new Thread(new ReceThread());
public static void main(String args[]) {
new ChatClient();
}
public ChatClient() {
add(tf, BorderLayout.SOUTH);
add(ta, BorderLayout.NORTH);
this.setSize(400, 300);
pack();
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});
tf.addActionListener(new TFlistener());
this.setTitle("在线聊天");
this.setLocationRelativeTo(null);
this.setVisible(true);
connect();
trece.start();
}
public void connect() {
try {
s = new Socket("localhost", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connect");
bconnection = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
* try { bconnection = false; trece.join();
*
*
* }catch (InterruptedException e) { e.printStackTrace(); } finally{ try
* { dos.close(); dis.close(); s.close(); } catch (IOException e) {
* e.printStackTrace(); } }
*/
}
private class TFlistener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tf.getText().trim();
tf.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class ReceThread implements Runnable {
public void run() {
try {
while (bconnection) {
String str = dis.readUTF();
ta.setText(ta.getText() + str + '\n' + '\n');
}
} catch (SocketException e) {
System.out.println("客户端已经退出");
}catch (EOFException e){
System.out.println("退出了――――――baybay!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}