?? chatclient.java
字號:
/*
* version 0.2
* 添加兩個控件
*/
/*
* version 0.3
* 添加TextField的監聽器
*/
/*
* version 0.4
* 添加連接Server端的功能
*/
/*
* version 0.5
* 發送一句話到服務器
* Socket s 由局部變量改為成員變量
*/
/*
* version 0.6
* 向服務器發送多句話
* 將DataOutputSream由局部變量改為成員變量
* 添加disConnect函數,用于關閉socket
*/
/*
* version 1.0
* client端添加接收各個client信息的功能
* 開一個ClientReceive線程進行接收
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient{
public static void main(String[] args){
new ChatClient().start();
}
private void start(){
ClientFrame cf = new ClientFrame("Client");
}
//Client窗口類
private class ClientFrame extends Frame{
TextField tf = null;
TextArea ta = null;
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
boolean isReceived = false;
public ClientFrame(String s){
super(s);
setBounds(300,300,400,300);
tf = new TextField();
ta = new TextArea();
//添加控件
add(tf,BorderLayout.SOUTH);
add(ta,BorderLayout.NORTH);
pack();
//添加關閉功能
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
//釋放資源
disConnected();
System.exit(0);
}
});
//為TextField添加監聽器
tf.addActionListener(new TFListener());
//與Server建立連接
connect2Server();
//接收各個client的數據
ClientReceive cr = new ClientReceive();
new Thread(cr).start();
//顯示窗體
setVisible(true);
}
//連接服務器端
private void connect2Server(){
try {
socket = new Socket("127.0.0.1",8888);
//添加通信管道
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
isReceived = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//接收其它Client的信息
private void receive(){
try{
while(isReceived){
String str = dis.readUTF();
ta.setText(ta.getText() + str +'\n');
}
} catch(SocketException e){
System.out.println("一個客戶端程序退出,bye");
} catch(IOException e){
e.printStackTrace();
} finally{
try {
if(dis!=null)
dis.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//斷開服務器,釋放資源
private void disConnected(){
try {
if(socket!=null)
socket.close();
if(dis!=null)
dis.close();
if(dos!=null)
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//添加TextField的監聽器類
private class TFListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//獲取TextField的內容
String str = tf.getText();
//設置TextArea的內容
//ta.setText(str);
tf.setText("");
//向Server發送信息
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
// client的接收線程,接收其它client的信息
private class ClientReceive implements Runnable{
public void run(){
receive();
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -