packagesocket_web;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;importjavax.websocket.OnClose;importjavax.websocket.OnMessage;importjavax.websocket.OnOpen;importjavax.websocket.Session;importjavax.websocket.server.ServerEndpoint;
@ServerEndpoint("/ChatRoomForWebSocket")public classChatRoomForWebSocket {public static List userNames = new ArrayList();public static List sessions = new ArrayList();
@OnOpenpublic voidopen(Session session) {try{
String userName=session.getQueryString();
userName= userName.split("=")[1];
userName= URLDecoder.decode(userName, "utf-8");if(userNames.contains(userName)) {
session.getBasicRemote().sendText("error");
}else{
userNames.add(userName);
sessions.add(session);
String msg= "{\"type\":0, \"data\":[" + jsonName() + "]}";
pushMsg(msg);
}
System.out.println(userName+ " 登入了");
}catch(Exception e) {
e.printStackTrace();
}
}
@OnClosepublic voidclose(Session session) {try{
String userName=session.getQueryString();
userName= userName.split("=")[1];
userName= URLDecoder.decode(userName, "utf-8");if(sessions.contains(session)){
userNames.remove(userName);
sessions.remove(session);
}
String msg= "{\"type\":0, \"data\":[" + jsonName() + "]}";
pushMsg(msg);
}catch(Exception e) {
System.out.println("关闭失败");
}
}
@OnMessagepublic voidmessage(Session session, String msg) {try{
String userName=session.getQueryString();
userName= userName.split("=")[1];
userName= URLDecoder.decode(userName, "utf-8");
Date date= newDate();
SimpleDateFormat timeFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=timeFormat.format(date);
msg= "{\"type\":1, \"data\":{\"name\":\"" + userName + "\", \"msg\":\"" + msg + "\",\"time\":\"" +time+ "\" }}";
pushMsg(msg);
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}//推送消息给所有用户
public static voidpushMsg(String msg) {try{for(Session session : sessions) {
session.getBasicRemote().sendText(msg);
}
}catch(Exception e) {
System.out.println("发送失败");
}
}//拼接所有用户名
public staticString jsonName() {
StringBuilder nameStr= new StringBuilder(100);for(String name : userNames) {
nameStr.append("{\"name\":\"" + name + "\"},");
}
nameStr.delete(nameStr.length()- 1, nameStr.length());returnnameStr.toString();
}
}