import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ChatClient extends Frame {
TextField tfTxt =new TextField(); //输入框
TextArea taContent = new TextArea(); //聊天信息框
Socket s = null;
DataInputStream dis= null;
DataOutputStream dos = null;
private boolean bConnected = false;
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 arg0) { //窗体关闭按钮的响应函数
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); //IP 和 端口
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
System.out.println("Connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
public void disconnect(){
/* try {
bConnected = false;
tRecv.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
} */
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//创建输入框监听器_内部类
private class TFListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable{
public void run(){
try{
while(bConnected){
String str;
str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
}catch(SocketException e){
System.out.println("退出了,bye!");
}catch(EOFException e){
System.out.println("退出了,bye-bye!");
}catch(IOException e){
e.printStackTrace();
}
}
}
}