springboot中websoket的使用

时间:2019-03-19 12:32:40   收藏:0   阅读:529

知识点:springboot项目中,websoket实时推送技术的介绍与使用

     一、双向通信

http协议通信只能由客户端发起请求,服务端返回查询结果,如果我们想定时获取服务端的状态变化,相对麻烦一点,Websoket协议之前,可以通过轮询,长轮询,iframe流的方式实现,我以前在一个项目里,做了一个用户抢登录的功能(一个账户同一时间只能由一个用户登录,如果之后有人登录,那么之前登录的用户就强制退出),用的是很简单的轮询,客户端定时向后台发请求,知道有新用户登录以后,则下线,但是缺点是轮询的间隔过长,会导致用户不能及时接收到更新的数据;轮询的间隔过短,会导致查询请求过多,增加服务器端的负担,所以如果服务器端一旦知道新用户登陆了,主动向客户端发消息,就避免了一些不必要的请求,可以用websoket技术

技术图片

技术图片

三:实现代码

1.引入mvn依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.启用WebSoket支持

@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}

3.server端:

@ServerEndpoint("/websocket_server")
@Component
public class WebSocketServer implements InitializingBean {
//静态变量,用来记录当前大屏数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
public static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;

/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //大屏数加1
System.out.println("有新连接加入!当前大屏数为" + getOnlineCount());
String message = "连接建立";
for(WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(){
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //大屏数减1
//screenFlagMap.remove(this.session.toString());
System.out.println("有一连接关闭!当前大屏数为" + getOnlineCount());
}

/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for(WebSocketServer item: webSocketSet){
try {
if(message.equals("ping")){
item.sendMessage("ping");
}else{
item.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* 实现服务器主动推送
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
/**
*以下都是实际业务的内容,根据业务进行编写
**/
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
@Override
public void afterPropertiesSet() throws Exception {
}
public WebSocketServer() {
}
}

4.消息推送,自己写个Controller,调用webSocketServer.sendMessage()
@Controller
@RequestMapping(value = "/screen")
public class APIController {

@Autowired
private WebSocketServer webSocketServer;

@RequestMapping(value = "/change")
@ResponseBody
public String skip(HttpServletRequest request, HttpServletResponse response) throws IOException {

//向所有客户端发送消息
String message="该账号已登录,强制下线";
WebSocketServer ws=new WebSocketServer();
Iterator< WebSocketServer> iterator = webSocketServer.webSocketSet.iterator();
while (iterator.hasNext()){
ws=iterator.next();
ws.sendMessage(message);
}
//webSocketServer.sendMessage(message);
return "操作成功!";
}
5.页面发起soket请求
<!DOCTYPE html>
<html>
<body>
<div>
WebSoket测试页
<div id="showInfo"></div>
</div>
<script>
debugger
var websocket = null;
var lockReconnect = false; //避免ws重复连接
//var wsUrl = "ws://${fns:getConfig(‘websocket.ip‘)}:${fns:getConfig(‘websocket.port‘)}/eip-si-screen/websocket";
var wsUrl="ws://192.168.1.105:5050/websocket_server";
createWebSocket(wsUrl);
function createWebSocket(url) {
try{
/**判断当前浏览器是否支持WebSocket**/
if (‘WebSocket‘ in window) {
websocket = new WebSocket(url);
}else if (‘MozWebSocket‘ in window){
websocket = new MozWebSocket(url);
}else {
alert(‘当前浏览器 Not support websocket‘)
}
initEventHandle(url);
}catch(e){
reconnect(url);
}
}
function initEventHandle(url) {

/* 连接发生错误的回调方法 */
websocket.onerror = function() {
reconnect(url);
setMessageInnerHTML("WebSocket连接发生错误");
};
/* 连接成功建立的回调方法 */
websocket.onopen = function() {
heartCheck.reset().start(); //心跳检测重置
setMessageInnerHTML("WebSocket连接成功");
}

/* 接收到消息的回调方法 */
websocket.onmessage = function(event) { //如果获取到消息,心跳检测重置
heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
setMessageInnerHTML(event.data);
if(event.data!=‘ping‘){
if(event.data.indexOf("{")!=-1){
console.log("eeeeee"+event.data);
}
}
}
/* 连接关闭的回调方法 */
websocket.onclose = function() {
reconnect(wsUrl);
setMessageInnerHTML("WebSocket连接关闭");
}
}

/* 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 */
window.onbeforeunload = function() {
closeWebSocket();
}
/* 将消息显示在网页上 */
function setMessageInnerHTML(innerHTML) {
document.getElementById("showInfo").innerHTML =innerHTML;
console.log("消息控制台打印:"+innerHTML);
}
/* 关闭WebSocket连接 */
function closeWebSocket() {
websocket.close();
}
/* 发送消息 */
function send() {
/* var message = document.getElementById(‘text‘).value; */
var message = ‘${pageCode}‘;
websocket.send(message);
}
function reconnect(url) {
if(lockReconnect) return;
lockReconnect = true;
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
createWebSocket(url);
lockReconnect = false;
}, 2000);
}

//心跳检测
var heartCheck = {
timeout: 59000, //9分钟发一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
websocket.send("ping");
console.log("ping!")
self.serverTimeoutObj = setTimeout(function(){ //如果超过一定时间还没重置,说明后端主动断开了
websocket.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}

</script>
<!--<script src="/js/org.js" type="text/javascript"></script>-->
</body>
</html>
function reconnect(url) {
if(lockReconnect) return;
lockReconnect = true;
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
createWebSocket(url);
lockReconnect = false;
}, 2000);
}

//心跳检测
var heartCheck = {
timeout: 59000, //9分钟发一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
websocket.send("ping");
console.log("ping!")
self.serverTimeoutObj = setTimeout(function(){ //如果超过一定时间还没重置,说明后端主动断开了
websocket.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}

</script>
<!--<script src="/js/org.js" type="text/javascript"></script>-->
</body>
</html>
function reconnect(url) {
if(lockReconnect) return;
lockReconnect = true;
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
createWebSocket(url);
lockReconnect = false;
}, 2000);
}

//心跳检测
var heartCheck = {
timeout: 59000, //9分钟发一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
websocket.send("ping");
console.log("ping!")
self.serverTimeoutObj = setTimeout(function(){ //如果超过一定时间还没重置,说明后端主动断开了
websocket.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
}

</script>
<!--<script src="/js/org.js" type="text/javascript"></script>-->
</body>
</html>

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!