?? chatserver.java
字號:
/*
* version 0.4
* 添加Server端
*/
/*
* version 0.5
* 添加接收客戶端的一句話的功能
*/
/*
* version 0.6
* 連續接收Client端的信息
*/
/*
* version 0.7
* 修正Client關閉時Server端的java.io.EOFException異常
* 出現該異常主要原因是資源沒有釋放
*/
/*
* version 0.8
* 使用多線程讓多個Client可以連接到Server
* 使用Client線程類實現
*/
/*
* version 0.9
* 將Server端接收到的數據發送到各個Client端
*/
import java.io.*;
import java.util.*;
import java.net.*;
public class ChatServer {
ServerSocket ss = null;
boolean isStarted = false;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
private void start() {
// 啟動Server監聽
try {
ss = new ServerSocket(8888);
isStarted = true;
} catch (BindException e) {
System.out.println("端口使用中......");
System.out.println("請重啟有關程序");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
// 處理Client的連接
try {
while(isStarted){
Socket socket = ss.accept();
Client c = new Client(socket);
new Thread(c).start();
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 處理Client的Client線程類
private class Client implements Runnable {
boolean isConnected = false;
Socket socket = null;
DataInputStream dis = null;
DataOutputStream dos = null;
public Client(Socket socket) {
this.socket = socket;
isConnected = true;
try {
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try{
while(isConnected){
String str = dis.readUTF();
System.out.println(str);
//向各個Client端發送數據
for(int i=0;i<clients.size();i++){
Client c = clients.get(i);
c.send(str);
}
}
} catch( EOFException e){
System.out.println("a client was disconnected!");
} catch(IOException e){
e.printStackTrace();
}
}
//發送信息到Client
public void send(String str){
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("a client quit!");
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -