📄 chatclient.java
字号:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
private static final long serialVersionUID = 1L;
TextField tf = new TextField();
TextArea ta = new TextArea();
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
String ServerIP = "";
Integer Port = 0;
boolean bConnected = false;
//String COMPUTERNAME = "";
String ip = "";
//InetAddress addr = null;
public static void main(String[] args) {
new ChatClient().lunchFrame();
}
private void lunchFrame() {
new ConnDialog();
setLocation(400,400);
setSize(400,400);
add(tf, BorderLayout.SOUTH);
add(ta, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0){
System.exit(0);
disConnect();
}
});
tf.addActionListener(new TFListener());
setVisible(true);
//COMPUTERNAME = System.getenv("COMPUTERNAME");
try {
ip = InetAddress.getLocalHost().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
}
connect();
new Thread(new RecvThread()).start();
}
public void connect(){
try {
s = new Socket(ServerIP, Port);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
} catch (SocketException e) {
System.out.println("Cann't find the server!");
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("connect!");
}
public void disConnect() {
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();
// ta.setText(str);
str = ip + ": " + str;
tf.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 = dis.readUTF();
ta.setText(ta.getText() + str + "\n");
}
}catch(SocketException se){
System.out.println("server is closed!");
}catch(IOException e){
e.printStackTrace();
}
}
}
private class ConnDialog extends Dialog{
TextField IPtf = new TextField("192.168.1.95", 12);
TextField Ptf = new TextField("8888", 4);
Button bt = new Button("确定");
public ConnDialog(){
super(ChatClient.this, true);
this.setLayout(new FlowLayout());
bt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ServerIP = IPtf.getText();
Port = Integer.parseInt(Ptf.getText().trim());
setVisible(false);
}
});
this.add(new Label("Server IP :"));
this.add(IPtf);
this.add(new Label("Port :"));
this.add(Ptf);
this.add(bt);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
}
});
this.pack();
setVisible(true);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -