[关闭]
@Toby-wei 2016-09-13T06:13:25.000000Z 字数 3181 阅读 2170

websocket聊天实现

websocket


前端连接

  1. (function(){
  2. var token = '' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000);
  3. $('#qr').attr('src', '/ih/bpv2/get-login-qrcode?token=' + token);
  4. tokenLast = token;
  5. var sockServerUrl = '/ws/socketio/';
  6. if(isPrd){
  7. sockServerUrl = 'http://ws.innohub.io/ws/socketio/';
  8. }
  9. sock = new SockJS(sockServerUrl);
  10. sock.onopen = function(){
  11. console.log('open');
  12. send({action: 'wx-auth-login-mapping-token-4-bpv2', token: tokenLast});
  13. };
  14. sock.onmessage = function(e){
  15. console.log(e.data);
  16. if(!e.data)
  17. return;
  18. var obj = JSON.parse(e.data);
  19. if(obj && 'reject' == obj.action){
  20. console.log('登陆失败');
  21. return;
  22. }
  23. if(obj && 'loginok' == obj.action){
  24. $.get('/ih/bpv2/front/login/done?token=' + tokenLast, function(data){
  25. var errs = {
  26. 'token-invalid': '令牌时效'
  27. };
  28. if(data.error){
  29. alert(errs[data.error]);
  30. return;
  31. }
  32. document.location.href = '/bp_20/detail-list.html';
  33. /* if(data.isAdmin){
  34. document.location.href = '/bp/manage.html';
  35. }else{
  36. }*/
  37. });
  38. return;
  39. }
  40. };
  41. })();
  42. window.onbeforeunload = function(){
  43. if(sock)
  44. sock.close();
  45. };
  46. });

发送消息

  1. // 发送文本消息
  2. handler.post('/ih/comm/message/send') { req, resp ->
  3. String openid = req.getCookie('user-login-openid')
  4. if (!openid) {
  5. resp.json([needRelogin: true])
  6. return
  7. }
  8. // 活跃度统计
  9. int active = StatActiveService.ACTIVE_HIGH
  10. StatActiveService.updateActive(openid, active)
  11. req.jsonHandler { json ->
  12. String toOpenid = json.toOpenid
  13. String content = json.content
  14. if (!toOpenid || !content) {
  15. log.info('send message blank')
  16. resp.json([error: 'content-blank'])
  17. return
  18. }
  19. // 判断是否关注
  20. boolean isFocus = WxUserLocal.isFocus(toOpenid)
  21. if (!isFocus) {
  22. resp.json([error: 'user-not-focused'])
  23. return
  24. }
  25. boolean isSendWsOk = MessageService.sendWs(config, handlerSockjs, openid, toOpenid, ipThis,
  26. MessageService.TYPE_TEXT, content)
  27. log.info('send message ws - ' + isSendWsOk)
  28. MessageService.add(openid, toOpenid, MessageService.TYPE_TEXT, content, isSendWsOk)
  29. // 看下对方用户是否在线,不在线就发送模板消息~
  30. if (!isSendWsOk) {
  31. // boolean isVisitOnline = MessageService.isMemberVisitOnline(config, toOpenid)
  32. boolean isPrd = 'true' == config.isPrd
  33. MessageService.sendTplMsg(openid, toOpenid, content, isPrd)
  34. }
  35. resp.json([flag: true])
  36. }
  37. }

发送方法

  1. // 推送websocket消息
  2. static boolean sendWs(Properties config, ChainHandlerSockjs handlerSockjs, String openid, String toOpenid, String ipThis,
  3. String type, String content) {
  4. Map wsInfo = isMemberWsOnline(config, openid, toOpenid)
  5. if (!wsInfo) {
  6. return false
  7. }
  8. String targetIp = wsInfo.targetIp
  9. String targetSockId = wsInfo.targetSockId
  10. // 目标用户的websocket链接是本机
  11. if (targetIp == ipThis) {
  12. Map fromUser = WxUserLocal.getUserByOpenid(openid)
  13. if (!fromUser) {
  14. // 不会发生
  15. log.info('user-not-subscribe')
  16. return false
  17. } else {
  18. boolean isOk = handlerSockjs.send(targetSockId, [type : type, content: content,
  19. fromOpenid: openid,
  20. nickname : fromUser.nickname, headimgurl: fromUser.headimgurl])
  21. log.info('send ws - ' + isOk)
  22. return isOk
  23. }
  24. } else {
  25. // 用http
  26. // for test TODO
  27. int port = 80
  28. String url = 'http://' + targetIp + ':' + port + '/ih/comm/message/send-message'
  29. log.info('redirect - ' + url)
  30. Map params = [:]
  31. params.targetSockId = targetSockId
  32. params.openid = openid
  33. params.type = type
  34. params.content = content
  35. String body = JSON.toJSONString(params)
  36. try {
  37. def req = HttpRequest.post(url).connectTimeout(1000 * 2).send(body)
  38. String str = req.body()
  39. log.info('redirect result ' + str)
  40. if (!str) {
  41. log.info('redirect by http return blank ' + toOpenid + ' - ' + targetSockId)
  42. return false
  43. } else {
  44. def resultSend = JSON.parse(str)
  45. return resultSend && resultSend.flag
  46. }
  47. } catch (e) {
  48. log.error('send message error - ' + toOpenid + ' - ' + targetSockId, e)
  49. return false
  50. }
  51. }
  52. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注