WebSocket使用示例

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

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

注意:
JDK必须是1.7以上版本,tomcat必须是7以上版本;
spring对Websocket的支持也是只有Spring4之后才有

1、编写客户端程序


<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;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值