import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
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().launchFrame();// 自身的对象调用方法
}
public void launchFrame() {
setLocation(400, 300);// 窗口的位置
this.setSize(300, 300);// 窗口的大小
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {// 关闭窗口
@Override
public void windowClosing(WindowEvent e) {
disconnect();// 关闭流
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);// 是否显示窗口
connect();
tRecv.start();//线程启动
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = 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 {
bConnected=false;
tRecv.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) {// 将输入的字符显示到 taContent 上
String str = tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");
try {// 利用 流 将客户端的数据发送到服务器
// DataOutputStream dos=new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
dos.flush();
// dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
String str;
try {
while (bConnected) {
str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText()+str+'\n');
}
} catch(SocketException e){
System.out.println(" 有点小问题,推出了!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}