首页 > 代码库 > [已解决]基于WebSocket开发聊天室应用
[已解决]基于WebSocket开发聊天室应用
WebSocket示例java的比较少,大部分是nodejs的,比较有名的是socket.io的chat,
借用下他的前端实现一套java的,后端基于nimbleio实现的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); } } }
演示地址:http://www.generallycloud.com/web-socket/chat/index.html
文章来自:http://www.cnblogs.com/gifisan/p/5946297.html
[已解决]基于WebSocket开发聊天室应用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。