📄 chatserver.java
字号:
} } } public void remoteJoinRoom(String server, String username, String roomname, String password) { boolean created = _distributedState.join(server, roomname, username); RoomServer room = (RoomServer)_rooms.get(roomKey(roomname)); if (room != null) { room.remoteJoin(username, password); } } public void remotePartRoom(String server, String username, String roomname, boolean isSignoff) { boolean destroyed = _distributedState.part(server, roomname, username); RoomServer room = (RoomServer)_rooms.get(roomKey(roomname)); if (room != null) { room.remotePart(username, isSignoff); } } public void joinRoom(ChatClient client, String roomName, String password) throws RoomJoinException { String key = roomKey(roomName); RoomServer room = (RoomServer)_rooms.get(key); if (room == null) { synchronized (_rooms) { room = (RoomServer)_rooms.get(roomKey(roomName)); if (room == null) { log(client.getUserId() + " created new room: " + roomName); room = createRoomServer(roomName, password); _rooms.put(roomKey(room), room); } } } room.join(client, password); _distributedState.join(getName(), room.getName(), client.getUserId()); } public void notifyClientsRoomCreated(String roomName) { synchronized (_users) { for (Iterator i = _users.values().iterator(); i.hasNext(); ) { ChatClient cc = (ChatClient)i.next(); cc.roomCreated(roomName); } } } public RoomServer createRoomServer(String roomName, String password) { return new RoomServer(roomName, password, this); } /** * returns a key for referencing the rooms hashmap. mainly to avoid * case-sensitivity problems. */ public static String roomKey(String room) { return room.toLowerCase(); } /** * returns a key for referencing the rooms hashmap. mainly to avoid * case-sensitivity problems. */ public static String roomKey(RoomServer room) { return roomKey(room.getName()); } /** * returns a key for referencing the users hashmap. mainly to avoid * case-sensitivity problems. */ public static String clientKey(ChatClient client) { return client.getKey(); } /** * returns a key for referencing the users hashmap. mainly to avoid * case-sensitivity problems. */ public static String clientKey(String client) { return client.toLowerCase(); } /** * Tells the server to begin accepting connections. */ protected void acceptConnections() { System.err.println("Chat Server listening on port " + _port); log("Accepting socket connections on port " + _port); while (_keepGoing) { try { Socket s = _serverSocket.accept(); s.setTcpNoDelay(true); // couldn't hurt log("Got a connection from " + s.getInetAddress().getHostAddress()); ChatClient client = createChatClient(s); _vulture.addClient(client); } catch (IOException e) { log(e); try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } } protected ChatClient createChatClient(Socket s) throws IOException { return new ChatClient(this, s); } public void pleaseStop() { _keepGoing = false; } /** * Get the names of all the rooms on this server * @return an array contains the names of all the rooms */ public String[] getRoomNames() { Collection c = _distributedState.getAllRooms(); String[] rooms = new String[c.size()]; c.toArray(rooms); return rooms; } public String[] getLocalRoomNames() { ArrayList al = new ArrayList(); synchronized (_rooms) { for (Iterator i = _rooms.values().iterator(); i.hasNext(); ) { RoomServer room = (RoomServer)i.next(); al.add(room.getName()); } } String[] rooms = new String[al.size()]; al.toArray(rooms); return rooms; } public String[] getServerNames() { Collection c = _distributedState.getAllServers(); String[] servers = new String[c.size()]; c.toArray(servers); return servers; } /** * Get the names of all the users on this server * @return an array contains the names of all the users */ public String[] getUserNames() { Collection c = _distributedState.getAllUsers(); String[] users = new String[c.size()]; c.toArray(users); return users; } public String[] getLocalUserNames() { ArrayList al = new ArrayList(); synchronized (_users) { for (Iterator i = _users.values().iterator(); i.hasNext(); ) { ChatClient client = (ChatClient)i.next(); al.add(client.getUserId()); } } String[] users = new String[al.size()]; al.toArray(users); return users; } public String[] getRoomsFor(ChatClient client) { String user = client.getUserId(); Vector rooms = new Vector(); synchronized (_rooms) { for (Iterator i = _rooms.values().iterator(); i.hasNext(); ) { RoomServer room = (RoomServer)i.next(); if (room.contains(client)) { rooms.add(room.getName()); } } } String[] srooms = new String[rooms.size()]; rooms.copyInto(srooms); return srooms; } /** * get the number of rooms currently on the server * @return the number of rooms */ public int getRoomCount() { return _rooms.size(); } /** * get the number of users currently on the server * @return the number of users */ public int getUserCount() { return _users.size(); } /** * Get the uptime * @return the uptime in milliseconds */ public long getUptime() { return System.currentTimeMillis() - _creationTime; } /** * Instantiate a ChatServer and start accepting connections */ public static void main(String[] args) { try { ChatServer server = null; if (args.length > 1) { if ("-f".equals(args[0])) { server = new ChatServer(args[1]); } } if (server == null) { server = new ChatServer(); } server.acceptConnections(); } catch (Exception e) { System.err.println("Error creating server"); e.printStackTrace(); } } protected static void createLoggers(String logFile, String errorLogFile) { if (logFile != null) { try { logger = new Logger(logFile, true); } catch (IOException e) { e.printStackTrace(); } } else { logger = new Logger(System.out); } if (errorLogFile != null) { try { errorLogger = new Logger(errorLogFile, true); } catch (IOException e) { e.printStackTrace(); } } else { logger = new Logger(System.err); } if (logger == null) { logger = new Logger(System.out); } if (errorLogger == null) { errorLogger = new Logger(System.err); } } protected static void showUsageAndExit() { System.err.println("usage: java com.lyrisoft.chat.server.remote.ChatServer port"); System.exit(1); } public void distribute(ChatClient client, String text) { if (_distributor == null || !_distributor.isConnected()) { return; } try { TextMessage message = _distributor.createTextMessage(); message.setStringProperty("origin", getName()); if (client != null) { message.setStringProperty("client", client.getUserId()); } message.setText(text); _distributor.push(message); } catch (JMSException e) { // this error is logged elsewhere } } /** * Incoming message from the Distributor (JMS) */ public void handleIncoming(javax.jms.Message message) { try { String origin = message.getStringProperty("origin"); if (getName().equals(origin)) { return; } String client = message.getStringProperty("client"); String text = ((TextMessage)message).getText(); CommandProcessorRemote.processDistributed(text, origin, client, this); } catch (JMSException e) { log(e); } } public String getName() { try { return java.net.InetAddress.getLocalHost().getHostName() + ":" + _port; } catch (java.net.UnknownHostException e) { throw new RuntimeException(e.toString()); } } public void announcePresence() { distribute(null, HELLO); distributeUserList(); distributeRoomList(); } public void distributeRoomList() { String[] roomNames = getLocalRoomNames(); if (roomNames.length == 0) { return; } StringBuffer sb = new StringBuffer(GET_ROOMS); sb.append(DELIMITER); for (int i=0; i < roomNames.length; i++) { String roomName = roomNames[i]; sb.append(roomNames[i]); sb.append(DELIMITER); } distribute(null, sb.toString()); for (int i=0; i < roomNames.length; i++) { distributeRoomState(roomNames[i]); } } public void distributeRoomState(String roomName) { RoomServer room = getRoom(roomName); if (room == null) { return; } String[] users = room.getUsers(); String msg = CommandMakerRemote.constructRoomUserListMessage(roomName, users); distribute(null, msg); } /** * If user list is blank, just send an empty reply. The * empty reply is important because it's the only way * somebody who just said /hello will see that we exist */ public void distributeUserList() { String[] userNames = getLocalUserNames(); StringBuffer sb = new StringBuffer(GET_USERS_ON_SERVER); sb.append(DELIMITER); for (int i=0; i < userNames.length; i++) { sb.append(userNames[i]); sb.append(DELIMITER); } distribute(null, sb.toString()); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- public int getUserCountInRoom(String roomName) { return _distributedState.countUsersInRoom(roomName); } public int getUserCountOnServer(String server) { return _distributedState.countUsersOnServer(server); } public String[] getUsersInRoom(String roomName) { Collection c = _distributedState.getUsersInRoom(roomName); String[] names = new String[c.size()]; c.toArray(names); return names; } public boolean userExists(String username) { return _distributedState.userExists(username); } public boolean serverExists(String servername) { return _distributedState.serverExists(servername); } public boolean roomExists(String roomname) { return _distributedState.roomExists(roomname); } public void checkServerPings(long timeout) { _distributedState.checkServerPings(timeout); } public void sendBroadcastPing() { distribute(null, BROADCAST_PING); } public void sendServerPing(String server) { StringBuffer sb = new StringBuffer(); sb.append(PING); sb.append(DELIMITER); sb.append(server); sb.append(DELIMITER); sb.append(System.currentTimeMillis()); distribute(null, sb.toString()); } public void sendServerPong(String server, String arg) { StringBuffer sb = new StringBuffer(); sb.append(PONG); sb.append(DELIMITER); sb.append(server); sb.append(DELIMITER); sb.append(arg); distribute(null, sb.toString()); } public void handlePong(String server, String arg) { try { long now = System.currentTimeMillis(); long delta = now - Long.valueOf(arg).longValue(); ChatServer.log("Ping reply from " + server + ": " + delta + " ms."); } catch (NumberFormatException e) { ChatServer.log(e); } } public void handleBroadcastPing(String server) { _distributedState.setLastBroadcastPing(server, System.currentTimeMillis()); } public static void DEBUG(String s) { if (DEBUG) { System.err.println(s); } } public static boolean getDebug() { String debug = System.getProperty("DEBUG"); if (debug == null) { return false; } return (new Boolean(debug)).booleanValue(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -