?? server.java
字號(hào):
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 類Server是游戲服務(wù)端方的主類。
**/
public class Server implements Runnable {
private int port = 6564; // 端口號(hào)
private Hashtable idcon = new Hashtable(); // 存儲(chǔ)與所有用戶的連接
private int id = 0;
static final String CRLF = "\r\n";
/** 每當(dāng)有新用戶加入時(shí),調(diào)用該函數(shù) */
synchronized void addConnection(Socket s) {
ClientConnection con = new ClientConnection(this, s, id);
id++;
}
/** 調(diào)用本函數(shù)來(lái)響應(yīng)客戶,set()跟蹤散列表idcon中的所有連接,防止
* 重復(fù)接受客戶的名字,調(diào)用setBusy()表示某個(gè)連接可以開(kāi)始游戲了。
* 對(duì)所有非忙連接,發(fā)出add消息通知這些游戲者這個(gè)新連接。
**/
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);
}
/** 響應(yīng)to消息,將body字符串的內(nèi)容直接寫入dest標(biāo)志的連接 */
synchronized void sendto(String dest, String body) {
ClientConnection con = (ClientConnection)idcon.get(dest);
if (con != null) {
con.write(body + CRLF);
}
}
/** 在body中,本方法向所有的除了在exclude中標(biāo)識(shí)的單個(gè)連接發(fā)送一個(gè)消息 */
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);
}
}
}
/** 本方法通知所有連接的客戶忘掉曾經(jīng)聽(tīng)過(guò)的the_id 。在客戶已經(jīng)開(kāi)始游戲
* 并將自己從可選的挑戰(zhàn)者表中刪除時(shí)使用
**/
synchronized void delete(String the_id) {
broadcast(the_id, "delete " + the_id);
}
/** 當(dāng)一個(gè)客戶發(fā)送quit消息,明確退出游戲,或當(dāng)用戶簡(jiǎn)單退出瀏覽器時(shí)
* 調(diào)用該方法
**/
synchronized void kill(ClientConnection c) {
if (idcon.remove(c.getId()) == c) {
delete(c.getId());
}
}
/** 本方法是服務(wù)器的主循環(huán),它在端口6564建立一個(gè)新套接字,然后進(jìn)入
* 無(wú)限循環(huán)等待客戶的套接字連接
**/
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()方法創(chuàng)建一個(gè)Server實(shí)例,然后啟動(dòng)一個(gè)新的線程來(lái)運(yùn)行 */
public static void main(String args[]) {
new Thread(new Server()).start();
try {
Thread.currentThread().join();
} catch (InterruptedException e) { }
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -