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;
}
}
分享到:
相关推荐
qt websocket 客户端代码 简单的websocket的示例代码
1、下载mongoose使用mongoose中的example中的websocket_chat,实现websocket 2、websocket_chat源码下载路径 官网:https://cesanta.com 论坛:https://forum.mongoose-os.com/index.php?p=/categories/mongoose ...
C# WebSocket 服务端和网页端示例,初学者必备!
go-websocket-examples Go语言WebSocket使用例子
WebSocket简单例子(包含一个WebSocket例子、一个SockJS例子、一个STOMP例子) 一个WebSocket例子:基于HTML5 一个SockJS例子:SockJS是对WebSocket做了封装,因为有些环境可能不支持WebSocket,SockJS会智能选择...
websocket小例子,不需要积分的;
spring-boot-websocket-client 代码示例
使用Noark创建的WebSocket服务器示例,客户端使用的Vue+WebSocket
Java版websocket示例 需要有java环境,直接启动jar包,打开页面即可。附带源代码
服务端是.net控制台程序,客户端是网页。本人从项目中快速抽离出来的,所以有很多没用的dll,还请谅解,关注websocket核心代码就好了。
可以在weblogic下开发的websocket完整示例,希望对你有用,谢谢!
netty-websocket-example 基于netty的websocket实现示例 高并发 附jmx压力测试
websocket使用完整实例,包含信息发送,接收。
html5的websocket代码示例包括错误解决方案
netty+websocket通讯例子
ASP.NET Core Web应用程序,包含服务端和客户端的示例代码(js)。
这是一个简单的Websocket示例工程(Spring Boot工程),演示了简单的Websocket使用方法。
java简单的websocket示例,需要tomcat-api.jar tomcat-juli.jar tomcat-coyote.jar
websocket实际列子,用vs2017编写的,包含服务端和客户端。 只需要将IP修改了就可以运行,可以 传输文本,图像,datatable数据
利用C++实现了websocket server, 使用libuv作为实现tcp的基础,另外使用gbase作为工具