引入3個文件
1.WebSocketConfig
package com.eastops.system.Interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.WebSocketServer
package com.eastops.system.Interceptor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eastops.common.core.utils.StringUtils;
import com.eastops.common.log.annotation.Log;
import com.eastops.system.controller.AppVersionController;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {
private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
/**靜態(tài)變量汹胃,用來記錄當前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的境蔼。*/
private static int onlineCount = 0;
/**concurrent包的線程安全Set驰凛,用來存放每個客戶端對應(yīng)的MyWebSocket對象北专。*/
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**與某個客戶端的連接會話阎姥,需要通過它來給客戶端發(fā)送數(shù)據(jù)*/
private Session session;
/**接收userId*/
private String userId="";
/**
* 連接建立成功調(diào)用的方法*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId=userId;
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
webSocketMap.put(userId,this);
//加入set中
}else{
webSocketMap.put(userId,this);
//加入set中
addOnlineCount();
//在線數(shù)加1
}
log.info("用戶連接:"+userId+",當前在線人數(shù)為:" + getOnlineCount());
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("用戶:"+userId+",網(wǎng)絡(luò)異常!!!!!!");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
//從set中刪除
subOnlineCount();
}
log.info("用戶退出:"+userId+",當前在線人數(shù)為:" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用戶消息:"+userId+",報文:"+message);
//可以群發(fā)消息
//消息保存到數(shù)據(jù)庫捐凭、redis
if(StringUtils.isNotBlank(message)){
try {
//解析發(fā)送的報文
JSONObject jsonObject = JSON.parseObject(message);
//追加發(fā)送人(防止串改)
jsonObject.put("fromUserId",this.userId);
String toUserId=jsonObject.getString("toUserId");
//傳送給對應(yīng)toUserId用戶的websocket
if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
}else{
log.error("請求的userId:"+toUserId+"不在該服務(wù)器上");
//否則不在這個服務(wù)器上拨扶,發(fā)送到mysql或者redis
}
}catch (Exception e){
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用戶錯誤:"+this.userId+",原因:"+error.getMessage());
error.printStackTrace();
}
/**
* 實現(xiàn)服務(wù)器主動推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群發(fā)消息
* @param message
* @throws IOException
*/
public static void BroadCastInfo(String message) throws IOException {
for (Map.Entry<String, WebSocketServer> stringWebSocketServerEntry : webSocketMap.entrySet()) {
stringWebSocketServerEntry.getValue().sendMessage(message);
}
// ------ 形式2 -------
// webSocketMap.forEach((k,v) -> {
// try {
// v.sendMessage(message);
// } catch (IOException e) {
// e.printStackTrace();
// }
// });
}
/**
* 發(fā)送自定義消息
* */
public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
log.info("發(fā)送消息到:"+userId+",報文:"+message);
if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage(message);
}else{
log.error("用戶"+userId+",不在線茁肠!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
3患民、SendPassagesController
package com.eastops.system.controller.screen;
import com.eastops.system.Interceptor.WebSocketServer;
import org.springframework.http.ResponseEntity;
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.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@RestController
public class SendPassagesController {
@GetMapping("index")
public ResponseEntity<String> index(){
return ResponseEntity.ok("請求成功");
}
@GetMapping("page")
public ModelAndView page(){
return new ModelAndView("websocket");
}
/**
* 定點單發(fā)
* @param message
* @param toUserId
* @return
* @throws IOException
*/
@RequestMapping("/push/{toUserId}")
public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {
WebSocketServer.sendInfo(message,toUserId);
return ResponseEntity.ok("MSG SEND SUCCESS");
}
/**
* 群發(fā)
* @param msg
* @throws IOException
*/
@RequestMapping("/broadcast")
public void broadcast(String msg) throws IOException {
WebSocketServer.BroadCastInfo(msg);
}
}
4.前端頁面 (注意改一下)
<!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");
//實現(xiàn)化WebSocket對象,指定要連接的服務(wù)器地址與端口 建立連接
//等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
//var socketUrl="${request.contextPath}/im/"+$("#userId").val();
var socketUrl="http://localhost:8080/system/imserver/"+$("#userId").val();
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
console.log(socketUrl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
//打開事件
socket.onopen = function() {
console.log("websocket已打開");
//socket.send("這是來自客戶端的消息" + location.href + new Date());
};
//獲得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//發(fā)現(xiàn)消息進入 開始處理前端觸發(fā)邏輯
};
//關(guān)閉事件
socket.onclose = function() {
console.log("websocket已關(guān)閉");
};
//發(fā)生了錯誤事件
socket.onerror = function() {
console.log("websocket發(fā)生了錯誤");
}
}
}
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="10"></div>
<p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
<p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:<div><a onclick="openSocket()">開啟socket</a></div>
<p>【操作】:<div><a onclick="sendMessage()">發(fā)送消息</a></div>
</body>
</html>
vue版本自行百度
后端向前端推送數(shù)據(jù)