📄 chatclient.java
字号:
import java.awt.*;
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 {
// 声明全局变量
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();//launch代表開始
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
this.setTitle("聊聊天工具");
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter(){
@Override//@為標記型語言
public void windowClosing(WindowEvent e) {
disconnect(); //窗口关闭时调用dos和s的关闭
System.exit(0);
}
});
TFListener tfl = new TFListener();
tfTxt.addActionListener(tfl);//当在文本域敲回车时,就执行TFListener类的actionPerformed方法
connect();
setVisible(true);
tRecv.start();
}
public void connect(){
try{
s = new Socket("127.0.0.1",8888);
dos = new DataOutputStream(s.getOutputStream());//一旦与服务器连接上,就把输出流赋值给dos
dis = new DataInputStream(s.getInputStream());
System.out.println("一个客户端已经连接上!");
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();//关闭线程,join方法为合并
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
private class TFListener implements ActionListener{//TFListener类用于实现TextField的监听;把TFListener类设为私有的内部类,是因为TFListener只是为ChatClient服务
@Override
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();//得到文本域的内容,并去掉两边空格,赋值给s
//taContent.setText(str);
tfTxt.setText("");
try{
dos.writeUTF(str);
dos.flush();
//dos.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable{
@Override
public void run() {
try {
while(bConnected){
String str = dis.readUTF();//当关闭时,会出错,是因为点击关闭按钮时,把管道Socket关掉了;所以要把dis和线程都停了
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch(SocketException e){
System.out.println("一个客户端已经退出,再见!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -