手机版
你好,游客 登录 注册
背景:
阅读新闻

WebSocket使用示例

[日期:2015-09-12] 来源:Linux社区  作者:muruiheng [字体: ]

HTML5给大家提供了一个很高大上的功能:WebSocket socket通信是在服务端与客户端之间进行的,所谓的WebSocket其实就是通过Html 与 后台服务器之间进行的消息传递;

下面我们来介绍一下如何实现一个简单的WebSocket实例。

注意:

JDK必须是1.7以上版本,tomcat必须是7以上版本;

spring对Websocket的支持也是只有Spring4之后才有

1、编写客户端程序

Html代码

<div class="row-fluid">
 <label>我要咨询
 </label>
 <label id="toUserName"></label>
 <div class="span12">
 <textarea rows="4" id="question_text" class="form-control"></textarea>
 </div>
</div>
<div class="row-fluid" style="margin-top: 10px;">
 <button id="btn_send" class="btn btn-default">发送</button>
 <button id="btn_cancel" class="btn btn-default">取消</button>
</div>
<hr>
<div class="row-fluid">
 <div class="span12" id="discussList">
 </div>
</div>

js代码

var webSocket =new WebSocket(resourceDomain.replace("http://", "ws://") + 'coder_request?wx101id='+wx101id);
 
webSocket.onerror = function(event) {
onError(event)
};

webSocket.onopen = function(event) {
onOpen(event)
};

webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
 var json =JSON.parse(event.data);
 var div = '<div class="thumbnail">';
 if (json.creator) {
  div = div +'<label>' + json.creator +'</label>';
 }
 div = div + '<div>' + json.content+ '</div>';
 div = div + '</div>';
 $("#discussList").prepend(div);
}

function onOpen(event) {
 userWebsocket = true;
}

function onError(event) {
   alert(event.data);
}

2、编写服务端程序

package com.itbuilder.wx.web.socket;

import Java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;

import com.itbuilder.framework.ApplicationContextHolder;
import com.itbuilder.framework.util.AssertUtil;
import com.itbuilder.framework.util.JSONUtil;
import com.itbuilder.wx.entity.Wxjc101;
import com.itbuilder.wx.entity.Wxjc102;
import com.itbuilder.wx.service.IWxjc102Service;
import com.itbuilder.wx.web.WebChatPool;


/**
 * 开发人员咨询socket
 * @author mrh
 *
 */
@Controller
@ServerEndpoint("/coder_request")
public class CoderRequestSocket {
 
 private IWxjc102Service wx102Service;
 
 /**
  * LOGGER
  */
 private static final Logger LOGGER = Logger.getLogger(CoderRequestSocket.class);
 
 

 public CoderRequestSocket() {
  this.wx102Service = ApplicationContextHolder.getBean("wx102Service", IWxjc102Service.class);
 }

 /**
  * 接收到开发人员发送的消息
  * @param message
  * @param session
  * @throws IOException
  * @throws InterruptedException
  */
 @OnMessage
 public void onMessage(String content, Session session) {
    try {
     String toUserName = this.getToUserName(content);
     String message = this.getMessage(content);
     String wx101id = this.getPoolId(session);
     Wxjc102 wx102 = this.wx102Service.doSendMsg(message, toUserName, wx101id);
     Wxjc101 wx101 = this.wx102Service.queryWx101(wx101id);
     Session reciver = WebChatPool.getSession(wx101id, wx101.getModifier());
   session.getBasicRemote().sendText(JSONUtil.toString(wx102));
   if (AssertUtil.hasValue(reciver) && !reciver.getId().equals(session.getId())) {
    reciver.getBasicRemote().sendText(JSONUtil.toString(wx102));
   }
   reciver = WebChatPool.getSession(wx101id, toUserName);
   if (AssertUtil.hasValue(toUserName) && !reciver.getId().equals(session.getId())) {
    reciver.getBasicRemote().sendText(JSONUtil.toString(wx102));
   }
  } catch (IOException e) {
   LOGGER.error("接受消息失败 sessionId = " + session.getId(), e);
  } catch (Exception e) {
   LOGGER.error("接受消息失败 sessionId = " + session.getId(), e);
  }
 }
 
 /**
  * 获取发送人信息
  * @param content String
  * @return String
  */
 private String getMessage(String content) {
  if (!AssertUtil.hasValue(content)) {
   return null;
  }
  if (!content.contains("&")) {
   return content;
  }
  return content.substring(0, content.lastIndexOf("&"));
 }
 
 /**
  * 获取发送人信息
  * @param content String
  * @return String
  */
 private String getToUserName(String content) {
  if (!AssertUtil.hasValue(content)) {
   return null;
  }
  if (!content.contains("&")) {
   return null;
  }
  return content.substring(content.lastIndexOf("&")+1, content.length());
 }
 
 /**
  * 链接打开之后将开发人员添加到回话池中
  * @param session
  */
 @OnOpen
 public void onOpen(Session session) {
  String poolId = this.getPoolId(session);
  if (AssertUtil.hasValue(poolId)) {
   WebChatPool.add(poolId, session.getId(), session);
  }
 }
 
 @OnClose
 public void onClose(Session session) {
  String poolId = this.getPoolId(session);
  if (AssertUtil.hasValue(poolId)) {
   WebChatPool.remvoe(poolId, session.getId());
  }
 }
 
 
 /**
  * 当前会话池ID
  * @param session
  * @return
  */
 private String getPoolId(Session session) {
  Map<String, List<String>> paramMap = session.getRequestParameterMap();
  if (AssertUtil.hasValue(paramMap)) {
   List<String> wx101IdList = paramMap.get("wx101id");
   if (AssertUtil.hasValue(wx101IdList)) {
    return wx101IdList.get(0);
   }
  }
  return null;
 }
}

本文永久更新链接地址http://www.linuxidc.com/Linux/2015-09/122944.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款