WebSocket sample Java is relatively small, mostly Nodejs, more famous is Socket.io's chat,
Borrow his front-end to implement a set of Java, the backend based on the Nimbleio implementation of WebSocket writing,
Directly on the code:
Public voidAccept (Session session, Readfuture future)throwsException {if(Futureinstanceofhttpreadfuture) { Super. Accept (Session, future); return; } websocketreadfuture F=(websocketreadfuture) future; //CLOSE if(F.gettype () = = 8) {msgadapter.removeclient (session); Jsonobject obj=NewJsonobject (); 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=NewWebsockettextreadfutureimpl (); 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); } } }
Demo Address: http://www.generallycloud.com/web-socket/chat/index.html
Article from: http://www.cnblogs.com/gifisan/p/5946297.html
[Resolved] Developer Chat room app based on WebSocket