WebSocket示例java的比较少,大部分是nodejs的,比较有名的是socket.io的chat,
借用下他的前端实现一套java的,后端基于https://github.com/generallycloud/baseio实现的WebSocket编写,
直接上代码:
public void accept(Session session, ReadFuture future) throws Exception { if (future instanceof HttpReadFuture) {
super.accept(session, future);
return;
} WebSocketReadFuture f = (WebSocketReadFuture) future; // CLOSE
if (f.getType() == 8) { msgAdapter.removeClient(session); JSONObject obj = new JSONObject(); obj.put("username", session.getAttribute("username"));
obj.put("numUsers", msgAdapter.getClientSize());
obj.put("action", "user-left"); String msg1 = obj.toJSONString(); msgAdapter.sendMsg(msg1); } else { // String msg = getMsg(session, ); String msg = f.getData().toString(Encoding.UTF8); JSONObject obj = JSONObject.parseObject(msg); String action = obj.getString("action"); if("new-message".equals(action)){ obj.put("username", session.getAttribute("username")); String msg1 = obj.toJSONString(); msgAdapter.sendMsg(msg1); }else if("add-user".equals(action)){ msgAdapter.addClient(session); String username = (String)session.getAttribute("username"); if(username != null){
return;
} username = obj.getString("username"); session.setAttribute("username", username); obj.put("numUsers", msgAdapter.getClientSize());
obj.put("action", "login"); String msg1 = obj.toJSONString(); WebSocketReadFutureImpl f2 = new WebSocketTextReadFutureImpl();
f2.write(msg1);
session.flush(f2); obj.put("username", username);
obj.put("action", "user-joined"); String msg2 = obj.toJSONString(); msgAdapter.sendMsg(msg2); }else if("typing".equals(action)){ obj.put("username", session.getAttribute("username")); String msg1 = obj.toJSONString(); msgAdapter.sendMsg(msg1); }else if("stop-typing".equals(action)){ obj.put("username", session.getAttribute("username")); String msg1 = obj.toJSONString(); msgAdapter.sendMsg(msg1); }else if("disconnect".equals(action)){ msgAdapter.removeClient(session); obj.put("username", session.getAttribute("username"));
obj.put("numUsers", msgAdapter.getClientSize());
obj.put("action", "user-left"); String msg1 = obj.toJSONString(); msgAdapter.sendMsg(msg1);
}else{ f.write("no action matched:"+action); session.flush(f);
}
}
}
演示地址:https://www.generallycloud.com/web-socket/chat/index.html