//server
public class NBChatServer {
private Selector sel;
private ServerSocketChannel server;
private ByteBuffer buf = ByteBuffer.allocate(1024);
// 保存 <name:channel> 的鍵值對,用於某一用戶向另一用戶發信息時,找到目標用戶的channel
private Hashtable<String, SocketChannel> sockets = new Hashtable<String, SocketChannel>();
// 保存 <key:name> 的鍵值對, 用於記錄某信息是哪個用戶發出的。
private Hashtable<SelectionKey, String> clients = new Hashtable<SelectionKey, String>();
public static boolean active = true;
public static final boolean NON_BLOCKING = false;
public static final String key_ip = "server.ip";
public static final String key_port = "server.port";
public static final String LOGIN_NO = "/login.no";
public static final String LOGIN_OK = "/login.ok";
private static Properties props = new Properties();
private static Pattern p = Pattern.compile("^\\>(.*?):(.*)$");
NBChatServer(String name) {
initConfig(name);
initServer();
startServer();
}
private static void initConfig(String fName) {
try {
InputStream in = NBChatServer.class.getClassLoader().getResourceAsStream(fName);
props.load(in);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
private void initServer() {
String portStr = props.getProperty(key_port);
int port = Integer.parseInt(portStr);
try {
sel = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(NON_BLOCKING);
InetAddress ip = InetAddress.getLocalHost();
InetSocketAddress sIp = new InetSocketAddress(ip, port);
server.socket().bind(sIp);
server.register(sel, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
private void startServer() {
int readyCount = 0;
while (active) {
try {
readyCount = sel.select();
} catch (IOException e) {
if (sel.isOpen())
continue;
else
e.printStackTrace();
}
if (readyCount == 0)
continue;
Set readyKeys = sel.selectedKeys();
Iterator keys = readyKeys.iterator();
while (keys.hasNext()) {
SelectionKey key = (SelectionKey) keys.next();
if (!key.isValid())
continue;
keys.remove();
// Acceptable: Tests whether this key's channel is ready to
// accept a new socket connection.
//
// Connectable:Tests whether this key's channel has either
// finished, or failed to finish, its socket-connection
// operation.
//
// Readable: Tests whether this key's channel is ready for
// reading.
//
// Writeable: Tests whether this key's channel is ready for
// writing.
try {
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel socket = (SocketChannel) ssc.accept();
socket.configureBlocking(NON_BLOCKING);
// socket 默認就有向緩衝區寫數據的權限,
// 如果爲socket向selector註冊OP_WRITE模式, 則selector將總能檢測到可寫操作,
// 於是select將總是立即返回, 導至CPU100%佔用。
// 這是該模式的一個bug.
socket.register(sel, SelectionKey.OP_READ);
}
if (key.isReadable()) {
SocketChannel srcSocket = (SocketChannel) key.channel();
buf.clear();
int nBytes = srcSocket.read(buf);
// 當客戶端關閉的時候,會向server端發最後一個空的信息,這時nBytes==-1;
if (nBytes == -1) {
teardownConn(key);
continue;
}
String input = ChatUtil.decode(buf);
String name = "all", msg = "", fromWho = null;
// 如果是login信息。則信息直接發給源socket。
if (input.startsWith("/login")) {
// login
String[] acct = input.substring(7).split("/");
name = acct[0];
String pwd = acct[1];
if (name.equals(pwd)) {
storeClient(name, srcSocket, key);
fromWho = this.getClientName(key);
msg = LOGIN_OK;
} else
msg = LOGIN_NO;
System.out.println(">>>" + msg);
srcSocket.write(ByteBuffer.wrap(msg.getBytes()));
}
// 如果是正常的聊天信息。則要從信息中解析出,信息要發給誰。
else {
// 解析信息開始
Matcher m = p.matcher(input);
if (m.find()) {
name = m.group(1);
msg = m.group(2);
} else {
name = ChatServer.ALL;
msg = input;
}
fromWho = this.getClientName(key);
if (fromWho != null)
msg = (">" + fromWho + " say:\n\t" + msg);
// 解析信息結束
System.out.println(msg);
ByteBuffer msgBuf = ByteBuffer.wrap(msg.getBytes());
if ("all".equals(name)) {
Iterator itr = sockets.keySet().iterator();
while (itr.hasNext()) {
name = (String) itr.next();
SocketChannel channel = this.getClient(name);
channel.write(msgBuf.duplicate());
}
} else {
SocketChannel dstSocket = this.getClient(name);
if (dstSocket == null)
dstSocket = srcSocket;
dstSocket.write(msgBuf);
}
}
// key.selector().wakeup();
}
} catch (IOException e) {
teardownConn(key);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}// while (keys.hasNext())
} // while (active)
}
private void teardownConn(SelectionKey key) {
String name = getClientName(key);
if (name != null) {
this.sockets.remove(name);
this.clients.remove(key);
}
key.cancel();
try {
key.channel().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("\n$Warn:" + name + " disconnect!");
}
private void storeClient(String name, SocketChannel socket, SelectionKey key) {
sockets.put(name, socket);
clients.put(key, name);
}
private SocketChannel getClient(String key) {
return sockets.get(key);
}
private String getClientName(SelectionKey key) {
return clients.get(key);
}
public static void stopSever() {
active = false;
}
public static void main(String[] args) {
new NBChatServer(args[0]);
}
}