?? chatclient.java
字號:
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;
TextField tfTxt = new TextField();
TextArea tfContent = new TextArea();
private boolean bConnect = false;
public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
setLayout(new BorderLayout());
add(tfTxt, BorderLayout.SOUTH);
add(tfContent, BorderLayout.NORTH);
pack();
// setSize(300,300);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
disConnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
connect();
setVisible(true);
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
bConnect = true;
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("Connect!");
new Thread(new RecvThread()).start();
}catch (ConnectException e) {
System.out.println("Can't find the server!");
System.exit(0);
}
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();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//tfContent.setText(str);
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnect) {
String str = null;
str = dis.readUTF();
tfContent.setText(tfContent.getText() + str + '\n');
}
} catch(SocketException e) {
System.out.println("退出!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -