HuaXinIM聊项目今天优化了:在线用户列表的实时更新。
每当有一个用户上线或者下线,数据库就会修改用户的在线状态信息,然后再发送给每一个用户。
代码:
当用户上线就设置状态'on',下线了就设置状态'off':
public boolean updateOn() throws Exception {
for(int i=0;i<IMServerMain.socketThreadList.size();i++){
String sql = "update user set online='on' where username='"
+IMServerMain.socketThreadList.get(i).user+"';";
UtilTemplete.update(sql);
}
return true;
}
public boolean updateOff(String user) throws Exception{
for(int i=0;i<IMServerMain.socketThreadList.size();i++){
String sql = "update user set online='off' where username='"
+user+"';";
UtilTemplete.update(sql);
}
return true;
}
新用户登录后,服务器发送给所有在线用户一个新的在线用户列表:
//更新数据后发送给其他所有的在线用户
for(int i=0;i<IMServerMain.socketThreadList.size();i++){
if(!IMServerMain.socketThreadList.get(i).user.equals(name)){
ArrayList<UserDatapojo> list = new MySQLDAOimpl().querygetHistoryMsg(
IMServerMain.socketThreadList.get(i).user);
String msg = "<choice>null</choice>"
+ "<username>null</username>"
+ "<type>getNewList</type>";
IMServerMain.socketThreadList.get(i).oos.writeUTF(msg);
IMServerMain.socketThreadList.get(i).oos.flush();
IMServerMain.socketThreadList.get(i).oos.writeObject(list);
IMServerMain.socketThreadList.get(i).oos.flush();
}
}
有用户下线后,也要发送一个新的在线用户列表给所有用户:
<span style="white-space:pre"> </span>try {
new MySQLDAOimpl().updateOff(this.user);//更新数据库数据
} catch (Exception e) {
e.printStackTrace();
}
IMServerMain.socketThreadList.remove(this);
//更新数据后发送给其他所有的在线用户
try{
for(int i=0;i<IMServerMain.socketThreadList.size();i++){
ArrayList<UserDatapojo> udpList = new MySQLDAOimpl().querygetHistoryMsg(
IMServerMain.socketThreadList.get(i).user);
String msg = "<choice>null</choice>"
+ "<username>null</username>"
+ "<type>getNewList</type>";
IMServerMain.socketThreadList.get(i).oos.writeUTF(msg);
IMServerMain.socketThreadList.get(i).oos.flush();
IMServerMain.socketThreadList.get(i).oos.writeObject(udpList);
IMServerMain.socketThreadList.get(i).oos.flush();
}
}catch(Exception e){
e.printStackTrace();
}
}
当用户在线列表更新后,查询数据库所有的在线用户(除了自己),然后整理成一个队列,发送给客户端,客户端实时更新。
登录的用户只有一个时:
登录两个:
登录三个:
登录四个:
下线一个用户:
又有一个用户下线: