在項目的開發時,遇到實現服務器主動發送數據到前端頁面的功能的需求。實現該功能不外乎使用輪詢和websocket技術,但在考慮到實時性和資源損耗後,最後決定使用websocket。現在就記錄一下用Java實現Websocket技術吧~
Java實現Websocket通常有兩種方式:1、創建WebSocketServer
類,裏面包含open、close、message、error等方法;2、利用Springboot提供的webSocketHandler
類,創建其子類並重寫方法。我們項目雖然使用Springboot框架,不過仍採用了第一種方法實現。
創建WebSocket的簡單實例操作流程
1)引入Websocket依賴
<!--websocket支持包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2)創建配置類WebSocketConfig
ServerEndpointExporter
是由Spring官方提供的標準實現,用於掃描ServerEndpointConfig
配置類和@ServerEndpoint
註解實例。
如果使用內置的tomcat容器,那麼必須用@Bean
注入ServerEndpointExporter
;
如果使用外置容器部署war包,那麼不需要提供ServerEndpointExporter
,掃描服務器的行爲將交由外置容器處理,需要將注入ServerEndpointExporter
的@Bean
代碼註解掉。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 如果使用Springboot默認內置的tomcat容器,則必須注入ServerEndpoint的bean;
* 如果使用外置的web容器,則不需要提供ServerEndpointExporter,下面的注入可以註解掉
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3)創建WebSocketServer
在websocket協議下,後端服務器相當於ws裏面的客戶端,需要用@ServerEndpoint
指定訪問路徑,並使用@Component
注入容器
@ServerEndpoint:當ServerEndpointExporter類通過Spring配置進行聲明並被使用,它將會去掃描帶有@ServerEndpoint註解的類。被註解的類將被註冊成爲一個WebSocket端點。所有的配置項都在這個註解的屬性中 ( 如:@ServerEndpoint("/ws") )
下面的栗子中@ServerEndpoint
指定訪問路徑中包含sid,這個是用於區分每個頁面
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint(value = "/ws/{sid}")
@Component
public class WebSocketServer {
private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
//舊:concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。由於遍歷set費時,改用map優化
//private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//新:使用map對象優化,便於根據sid來獲取對應的WebSocket
private static ConcurrentHashMap<String,WebSocketServer> websocketMap = new ConcurrentHashMap<>();
//接收用戶的sid,指定需要推送的用戶
private String sid;
/**
* 連接成功後調用的方法
*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
//webSocketSet.add(this); //加入set中
websocketMap.put(sid,this); //加入map中
addOnlineCount(); //在線數加1
log.info("有新窗口開始監聽:"+sid+",當前在線人數爲" + getOnlineCount());
this.sid=sid;
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("websocket IO異常");
}
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
if(websocketMap.get(this.sid)!=null){
//webSocketSet.remove(this); //從set中刪除
websocketMap.remove(this.sid); //從map中刪除
subOnlineCount(); //在線數減1
log.info("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
}
/**
* 收到客戶端消息後調用的方法,根據業務要求進行處理,這裏就簡單地將收到的消息直接羣發推送出去
* @param message 客戶端發送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到來自窗口"+sid+"的信息:"+message);
if(StringUtils.isNotBlank(message)){
for(WebSocketServer server:websocketMap.values()) {
try {
server.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
/**
* 發生錯誤時的回調函數
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發生錯誤");
error.printStackTrace();
}
/**
* 實現服務器主動推送消息
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 羣發自定義消息(用set會方便些)
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送內容:"+message);
/*for (WebSocketServer item : webSocketSet) {
try {
//這裏可以設定只推送給這個sid的,爲null則全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}*/
if(StringUtils.isNotBlank(message)){
for(WebSocketServer server:websocketMap.values()) {
try {
// sid爲null時羣發,不爲null則只發一個
if (sid == null) {
server.sendMessage(message);
} else if (server.sid.equals(sid)) {
server.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4)websocket調用
可以提供接口讓前端調用,也可以由前端指定ws調用網址,直接使用onopen等方法。在業務代碼中調用方法也是可以的。
4.1)提供接口進行消息推送
一個用戶調用接口,主動將信息發給後端,後端接收後再主動推送給指定/全部用戶
import com.javatest.websocket.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/websocket")
public class WebSocketController {
//頁面請求
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav=new ModelAndView("/socket");
mav.addObject("cid", cid);
return mav;
}
//推送數據接口
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public Map<String,Object> pushToWeb(@PathVariable String cid, String message) {
Map<String,Object> result = new HashMap<>();
try {
WebSocketServer.sendInfo(message,cid);
result.put("status","success");
} catch (IOException e) {
e.printStackTrace();
result.put("status","fail");
result.put("errMsg",e.getMessage());
}
return result;
}
}
4.2)由前端指定ws調用網址直接使用
前端頁面,注意是要使用ws協議
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket通訊</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var socket;
function openSocket() {
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else{
console.log("您的瀏覽器支持WebSocket");
//實現化WebSocket對象,指定要連接的服務器地址與端口 建立連接
//等同於socket = new WebSocket("ws://localhost:9010/javatest/ws/25");
//var socketUrl="${request.contextPath}/ws/"+$("#userId").val();
var socketUrl="http://localhost:9010/javatest/ws/"+$("#userId").val();
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
console.log(socketUrl)
socket = new WebSocket(socketUrl);
//打開事件
socket.onopen = function() {
console.log("websocket已打開");
//socket.send("這是來自客戶端的消息" + location.href + new Date());
};
//獲得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//發現消息進入 開始處理前端觸發邏輯
};
//關閉事件
socket.onclose = function() {
console.log("websocket已關閉");
};
//發生了錯誤事件
socket.onerror = function() {
console.log("websocket發生了錯誤");
}
}
}
function sendMessage() {
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else {
console.log("您的瀏覽器支持WebSocket");
console.log('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
socket.send('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
}
}
</script>
<body>
<p>【userId】:<div><input id="userId" name="userId" type="text" value="11"/></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="22"/></div>
<p>【toUserId內容】:<div><input id="contentText" name="contentText" type="text" value="abc"/></div>
<p>【操作】:<div><input type="button" onclick="openSocket()"/>開啓socket</div>
<p>【操作】:<div><input type="button" onclick="sendMessage()"/>發送消息</div>
</body>
</html>
這樣,啓動服務器之後就可以接口或者ws調用網址的方式進行websocket的通信啦~
參考文獻:
WebSocket實踐——Java實現WebSocket的兩種方式
Java/WebSocket的實現
SpringBoot2.0集成WebSocket,實現後臺向前端推送信息