使用WebSocket推送服务器消息
1. 用户登录后通过js脚本创建websoket对象, 与服务器握手 2. 3. 4. 5. 6. var url = 'ws://localhost:8080/websocket/WebSocket?clientId='+clientId; CallCenter.init(url); var CallCenter = { init:function(url){ 7. var _websocket = new WebSocket(url); 8. 9. _websocket.onopen = function(evt) { 10. console.log(\ 11. }; 12. _websocket.onclose = function(evt) { 13. console.log(\ 14. }; 15. 16. //当登录者接受到新消息时,显示收件信息 17. _websocket.onmessage = function(evt) { 18. alert(evt.data); 19. }; 20. 21. _websocket.onerror = function(evt) { 22. console.log('Error occured: ' + evt); 23. }; 24. } 25. };
2. 创建对象
public class WebSocket extends WebSocketServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet() */
public WebSocket() { super(); } /**
* 客户端连接后会调用此方法,创建StreamInbound对象 * */
@Override
protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) {
String clientId = request.getParameter(\ return new CallCenterMessageInBound(clientId); }
}
3. 将当前登录者信息列入socketList集合中, 创建添加、移除和发送方法
1. 2. 3. public class CallCenterMessageInBound extends MessageInbound { private String clientId; public static final Map
4. js调用发送方法,给指定的用户发送消息
1. 2. 3. 4. 5. 6. 7. 8. 9. $(document).ready(function(){ $(\ $.ajax({ type: \ url: \ data: \clientId=\#clientId\message=\#message\ success: function(msg){ alert(msg.message); } 10. }); 11. }); 12. }); 13. @Controller 14. public class MessageAPI { 15. /** 16. * 向客户端推送消息 17. * */ 18. @ResponseBody 19. @RequestMapping(value = \) 20. public Map