[已解决][HTML5]基于WebSocket开发小蝌蚪应用
前端时间在网上看到别人用WebSocket开发的小蝌蚪应用很炫酷,不过是php,于是想着用java也实现一套,
找到前端 https://github.com/danielmahal/Rumpetroll ,膜拜大神,自己写不来,拿来借用下~
后端基于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 o = new JSONObject(); o.put("type", "closed"); o.put("id", session.getSessionID()); msgAdapter.sendMsg(o.toJSONString()); logger.info("客户端主动关闭连接:{}", session); } else { String msg = f.getData().toString(Encoding.UTF8); JSONObject o = JSONObject.parseObject(msg); String name = o.getString("name"); if (StringUtil.isNullOrBlank(name)) { name = getAddress(session); } o.put("name", name); o.put("id", session.getSessionID()); String type = o.getString("type"); if ("update".equals(type)) { o.put("life", "1"); o.put("authorized", "false"); o.put("x", Double.valueOf(o.getString("x"))); o.put("y", Double.valueOf(o.getString("x"))); o.put("momentum", Double.valueOf(o.getString("momentum"))); o.put("angle", Double.valueOf(o.getString("angle"))); } else if ("message".equals(type)) { } msgAdapter.sendMsg(o.toJSONString()); } } private String getAddress(Session session) { String address = (String) session.getAttribute("_remote_address"); if (address == null) { address = session.getRemoteSocketAddress().toString(); session.setAttribute("_remote_address", address); } return address; }
演示地址:https://www.generallycloud.com/web-socket/rumpetroll/index.html
文章来自:http://www.cnblogs.com/gifisan/p/5946247.html
轻量级 Java NIO 工具包:https://github.com/generallycloud/baseio