System.out.print(\ /* * 给本线程用户发送在线用户列表 */ list群聊(); /* * 将本用户加入集合 */ users.put(this.username, this); } String msg = \ String touser = \群聊\ while (!s.isClosed()) { while (!s.isClosed() && (msg = in.readLine()) != null && msg.length() > 0) { /* * 收到用户退出的系统信息,删除集合中对应项,通知所有用户 */ if (msg.startsWith(SYSTEM_MSG + USER_LOGOUT)) { synchronized (lock) { users.remove(this.username); } send群聊(SYSTEM_MSG + DELETE_USER + this.username); s.close(); System.out.print(\ } /* * 收到聊天信息,解析出发送对象和信息内容,并发送 */ else { touser = msg.substring(0, msg.indexOf(NAME_END)); msg = msg.replaceFirst(touser + NAME_END, \ send(msg, touser); } } } } /* * 登陆时出现用户名已存在情况,通知用户 */
25
}
catch (ExistException e) { out.println(SYSTEM_MSG + USER_EXIST); out.flush();
} catch (Exception e) { } finally { try { s.close(); } catch (Exception e) { } }
/**
* 发送信息给所有用户 */
private void send群聊(String msg) { Set s = users.keySet(); Iterator it = s.iterator(); while (it.hasNext()) { UserThread t = (UserThread) users.get(it.next()); if (t != this) t.sendUser(msg); } }
/**
* 给本线程发送在线用户列表 */
private void list群聊() { Set s = users.keySet(); Iterator it = s.iterator(); while (it.hasNext()) { this.sendUser(SYSTEM_MSG + EXIST_USERS + it.next()); } }
/**
* 判断用户名是否已经有人使用 */
private boolean isExist(String name) { Set s = users.keySet(); Iterator it = s.iterator(); while (it.hasNext()) { if (name.equals((String) it.next())) {
26
return true; } } return false; } /** * 给本线程对应的用户发信息 */ private void sendUser(String msg) { out.println(msg); out.flush(); // System.out.println(\调试用代码 } /** * 给指定对象发送信息 */ private void send(String msg, String touser) { /* * 调用相应函数,给所有人发信息时 */ if (touser.equals(\群聊\ send群聊(this.username + NAME_END + msg); return; } /* * 根据发送目标的名字获得相应线程,调用目标线程的函数给目标发送信息 */ if (users.containsKey(touser))// 加判断,防止用户已经离线 ((UserThread) users.get(touser)).sendUser(MSG_FROM + this.username + NAME_END + msg); } }
/**
* 主方法:启动服务器 */
public static void main(String[] args) { /* * 根据参数的情况,获得端口号,无效时使用默认值,并返回相应信息 */
27
}
}
int port = DEFAULT_PORT; if (args.length > 0) { int newport; try { newport = Integer.parseInt(args[0]); /* * 无效端口 */ if (newport > 65535 || newport < 0) { System.out.println(\ } /* * 操作系统预留端口 */ else if (newport <= 1024) { System.out.println(\ } else { port = newport; } } /* * 不能转换成整数的参数 */ catch (NumberFormatException e) { System.out.println(\ } } try { ServerSocket ss = new ServerSocket(port); System.out.print(\ while (true) { Socket s = ss.accept(); Thread t = new UserThread(s); t.start(); } } /*
* 端口绑定失败 */
catch (IOException e) { System.out.println(\}
28