?? chatclientsocket.java
字號(hào):
import java.net.*;
import java.io.*;
import javax.swing.JOptionPane;
// 處理客戶端連線的Thread
public class ChatClientSocket extends Thread {
private Socket skt; // 客戶端連線Socket物件
private InetAddress host; // 指定的伺服端IP
private int port; // 指定的伺服端連接埠
private BufferedReader theInputStream;
private PrintStream theOutputStream;
private String message; // 伺服端傳回的資料
private MultiChatClient chatBox; // 聊天程式介面
public ChatClientSocket(String ip, int port) {
try {
// 取得伺服端的InetAddress物件、通訊連接埠
host = InetAddress.getByName(ip);
this.port = port;
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, e.toString(),
"錯(cuò)誤", JOptionPane.ERROR_MESSAGE);
}
}
// 指定這個(gè)Socket的訊息觀察者
public void setMessageObserver(MultiChatClient box) {
chatBox = box;
}
// 取得訊息
public String getMessage() {
return message;
}
public void run() {
try {
message = "嘗試連線......";
chatBox.update();
// 建立Socket物件並嘗試連線
skt = new Socket(host, port);
message = "連線成功\n";
chatBox.update();
// 從InputStream建立讀取緩衝區(qū)
theInputStream = new BufferedReader(
new InputStreamReader(skt.getInputStream()));
// 從OutputStream中建立PrintStream物件
theOutputStream = new PrintStream(skt.getOutputStream());
// 讀取資料迴圈
while((message = theInputStream.readLine()) != null) {
// 將之顯示在Applet的TextArea上
message = ": " + message + "\n";
chatBox.update();
}
if(message == null) {
skt.close();
message = "連線中斷!\n";
chatBox.update();
chatBox.setGUIState(true);
}
}
catch (IOException e) {
message = e.toString();
chatBox.update();
}
}
// 客戶端丟出資料的方法
public void dataOutput(String data) {
theOutputStream.println(data);
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -