📄 chatclient.java
字号:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame{
TextArea ta = new TextArea();
TextField tf = new TextField();
Socket s = null;
DataOutputStream dos = null;
DataInputStream dd = null;
private boolean bConnected = false;
Thread tRecv = new Thread(new RecvThread());
public void launchFrame() {
this.setLocation(100, 100);
this.setSize(600,300);
this.setTitle("小高TCP聊天器");
add(ta, BorderLayout.NORTH);
add(tf, BorderLayout.SOUTH);
pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}});
tf.addActionListener(new TFListener());
this.setVisible(true);
connect();
tRecv.start();
}
public static void main(String[] args) {
ChatClient c = new ChatClient();
c.launchFrame();
}
public class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tf.getText().trim();
//ta.setText(str);
tf.setText("");
try {
dos.writeUTF(str);
dos.flush();
}catch(IOException e1) {
e1.printStackTrace();
}
}
}
public void connect() {
try {
s = new Socket("127.0.0.1",8888);
System.out.println("已连上服务端");
dos = new DataOutputStream(s.getOutputStream());
dd = new DataInputStream(s.getInputStream());
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
s.close();
dd.close();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dd.readUTF();
//System.out.println(str);
ta.setText(ta.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("退出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -