springboot+websocket 概括收集


websocket是h5後的技術,主要實現是一個長鏈接跟tomcat的comet技術差很少,但websocket是基於web協議的,有更普遍的支持。固然,在處理高併發的狀況下,能夠結合tomcat的asyncContext來實現長處理的異步返回等操做。html

1.引入依賴類前端

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>

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

這裏主要是引入websocket的依賴類java

2.springboot配置websocket的入口beanjquery

在springboot的配置類下,引入如下的配置beangit

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

3.實現websocket的後端處理邏輯github

package com.ouyang.server;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
* Created by Administrator on 2018/3/25.
*/

//@Slf4j
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {

Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//靜態變量,用來記錄當前在線鏈接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
// 備用的同步hashmap
//private static ConcurrentHashMap<Session,WebSocketServer> webSocketServerConcurrentHashMap = new ConcurrentHashMap();

//與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據
private Session session;

/**
* 鏈接創建成功調用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
log.info("有新鏈接加入!當前在線人數爲" + getOnlineCount());
try {
sendMessage("鏈接成功");
} catch (IOException e) {
log.error("websocket IO異常");
}
}
// //鏈接打開時執行
// @OnOpen
// public void onOpen(@PathParam("user") String user, Session session) {
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// }

/**
* 鏈接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
log.info("有一鏈接關閉!當前在線人數爲" + getOnlineCount());
}

/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("來自客戶端的消息:" + message);

//羣發消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage("response message:"+message);
} catch (IOException e) {
e.printStackTrace();
}
}
//單發的信息
sendMessage("currentWebsocket is ok!!! ");
}

/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發生錯誤");
error.printStackTrace();
}

/**
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}


/**
* 羣發自定義消息
* */
public static void sendInfo(String message) throws IOException {
//log.info(message);
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}

public static synchronized int getOnlineCount() {
return onlineCount;
}

public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}

public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}

 

至此,咱們關於後臺的websocket的主要實現類都實現了,接下來咱們能夠弄一個,測試的接口,用於給全部的websocket推送信息,以下:web

 

@RequestMapping(value="/publicSend",method= RequestMethod.GET)
@ResponseBody
public String pushVideoListToWeb2(String id) {
try {
WebSocketServer.sendInfo("有新客戶呼入,sltAccountId:"+id);
for(int i= 0;i<20;i++){
WebSocketServer.sendInfo("有新客戶呼入,testing:"+String.valueOf(i));
}
}catch (IOException e) {

}
return "success!";

}

4.前端測試頁面的實現spring

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.springframework.org/schema/jdbc">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/jquery.js"></script>
<script src="/static/stomp.min.js"></script>
<script src="/static/sockjs.min.js"></script>
<script>
//socket = new WebSocket("ws://localhost:8081/begenstom/websocket");
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else {
console.log("您的瀏覽器支持WebSocket");

//實現化WebSocket對象,指定要鏈接的服務器地址與端口
//socket = new WebSocket("ws://localhost:9094/starManager/websocket/張三");
socket = new WebSocket("ws://localhost:8081/websocket");
//打開事件
socket.onopen = function () {
console.log("Socket 已打開");
for (var i=0;i<20;i++)
{
socket.send("這是來自客戶端的消息1:" + i);
}
//socket.send("這是來自客戶端的消息" + location.href + new Date());
};
//得到消息事件
socket.onmessage = function (msg) {
console.log(msg.data);
//發現消息進入 調後臺獲取
document.write(msg.data);
};
//關閉事件
socket.onclose = function () {
console.log("Socket已關閉");
};
//發生了錯誤事件
socket.onerror = function () {
alert("Socket發生了錯誤");
}
$(window).unload(function () {
socket.close();
});
}
</script>


</head>
<body>

</body>
</html>

這裏主要用到3個js,能夠去github上去當一個。後端

 

測試結果:==================瀏覽器

參考地址:* https://blog.csdn.net/zhangdehua678/article/details/78913839* https://github.com/ayman-elgharabawy/Kafka-SpringBoot-WebSocket* 整合框架 https://github.com/527515025/springBoot

相關文章
相關標籤/搜索