?? server.java
字號:
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 類Server是游戲服務端方的主類。
**/
public class Server implements Runnable {
private int port = 6564; // 端口號
private Hashtable idcon = new Hashtable(); // 存儲與所有用戶的連接
private int id = 0;
static final String CRLF = "\r\n";
/** 每當有新用戶加入時,調用該函數 */
synchronized void addConnection(Socket s) {
ClientConnection con = new ClientConnection(this, s, id);
id++;
}
/** 調用本函數來響應客戶,set()跟蹤散列表idcon中的所有連接,防止
* 重復接受客戶的名字,調用setBusy()表示某個連接可以開始游戲了。
* 對所有非忙連接,發出add消息通知這些游戲者這個新連接。
**/
synchronized void set(String the_id, ClientConnection con) {
idcon.remove(the_id) ;
con.setBusy(false);
Enumeration e = idcon.keys();
while (e.hasMoreElements()) {
String id = (String)e.nextElement();
ClientConnection other = (ClientConnection) idcon.get(id);
if (!other.isBusy())
con.write("add " + other + CRLF);
}
idcon.put(the_id, con);
broadcast(the_id, "add " + con);
}
/** 響應to消息,將body字符串的內容直接寫入dest標志的連接 */
synchronized void sendto(String dest, String body) {
ClientConnection con = (ClientConnection)idcon.get(dest);
if (con != null) {
con.write(body + CRLF);
}
}
/** 在body中,本方法向所有的除了在exclude中標識的單個連接發送一個消息 */
synchronized void broadcast(String exclude, String body) {
Enumeration e = idcon.keys();
while (e.hasMoreElements()) {
String id = (String)e.nextElement();
if (!exclude.equals(id)) {
ClientConnection con = (ClientConnection) idcon.get(id);
con.write(body + CRLF);
}
}
}
/** 本方法通知所有連接的客戶忘掉曾經聽過的the_id 。在客戶已經開始游戲
* 并將自己從可選的挑戰者表中刪除時使用
**/
synchronized void delete(String the_id) {
broadcast(the_id, "delete " + the_id);
}
/** 當一個客戶發送quit消息,明確退出游戲,或當用戶簡單退出瀏覽器時
* 調用該方法
**/
synchronized void kill(ClientConnection c) {
if (idcon.remove(c.getId()) == c) {
delete(c.getId());
}
}
/** 本方法是服務器的主循環,它在端口6564建立一個新套接字,然后進入
* 無限循環等待客戶的套接字連接
**/
public void run() {
try {
ServerSocket acceptSocket = new ServerSocket(port);
System.out.println("Server listening on port " + port);
while (true) {
Socket s = acceptSocket.accept();
addConnection(s);
}
} catch (IOException e) {
System.out.println("accept loop IOException: " + e);
}
}
/** main()方法創建一個Server實例,然后啟動一個新的線程來運行 */
public static void main(String args[]) {
new Thread(new Server()).start();
try {
Thread.currentThread().join();
} catch (InterruptedException e) { }
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -