springboot 項目==基於websocket的服務端推送消息。

1.建立springboot項目,首先咱們仍是先引入依賴


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

2.建立配置類   WebSocketH5Config

@Configuration
@EnableWebSocket
public class WebSocketH5Config implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//handler是webSocket的核心,配置入口
registry.addHandler(new MyHandler(), "/myHandler/{ID}").setAllowedOrigins("*").addInterceptors(new WebSocketInterceptor());
}

3.建立服務類   MyHandler

@Service
public class MyHandler implements WebSocketHandler {

//在線用戶列表
private static final Map<String, WebSocketSession> users;

static {
users = new HashMap<>();
}

//新增socket
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String ID = session.getUri().toString().split("ID=")[1];
//使用URLDecoder進行解碼,由於前段傳來的就是亂碼
String decode = URLDecoder.decode(ID, "UTF-8");
System.out.println("成功創建鏈接,註冊帳號爲" + decode);
if (decode != null) {
users.put(decode, session);
session.sendMessage(new TextMessage("成功創建socket鏈接"));
System.out.println(session);
}
System.out.println("當前在線人數:" + users.size());
}

//接收socket信息(接受客戶端的信息)
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
try {
JSONObject jsonobject = JSONObject.fromObject(webSocketMessage.getPayload());
// System.out.println(jsonobject.get("id"));
// System.out.println(jsonobject.get("message") + ":來自" + (String) webSocketSession.getAttributes().get("WEBSOCKET_USERID") + "的消息");
Map map = new HashMap(2);
map.put("id", jsonobject.get("id"));
map.put("message", jsonobject.get("message").toString());
String msg = JSON.toJSONString(map);
//將消息發送到mq
Sender been = (Sender) AppContext.getBeen(Sender.class);
been.send(msg);
sendMessageToUser(jsonobject.get("id") + "", new TextMessage(msg));
} catch (Exception e) {
e.printStackTrace();
}

}

/**
* 發送信息給指定用戶 (服務端給指定用戶發送消息)
*
* @param clientId
* @param message
* @return
*/
public boolean sendMessageToUser(String clientId, TextMessage message) {
if (users.get(clientId) == null) return false;
WebSocketSession session = users.get(clientId);
// System.out.println("sendMessage:" + session);
if (!session.isOpen()) return false;
try {
session.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 廣播信息(服務端給全部用戶推送消息)
*
* @param message
* @return
*/
public boolean sendMessageToAllUsers(TextMessage message) {
boolean allSendSuccess = true;
Set<String> clientIds = users.keySet();
WebSocketSession session = null;
for (String clientId : clientIds) {
try {
session = users.get(clientId);
if (session.isOpen()) {
session.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
allSendSuccess = false;
}
}

return allSendSuccess;
}


@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
System.out.println("鏈接出錯");
users.remove(getClientId(session));
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("鏈接已關閉:" + status);
users.remove(getClientId(session));
}

@Override
public boolean supportsPartialMessages() {
return false;
}

/**
* 獲取用戶標識
*
* @param session
* @return
*/
private Integer getClientId(WebSocketSession session) {
try {
Integer clientId = (Integer) session.getAttributes().get("WEBSOCKET_USERID");
return clientId;
} catch (Exception e) {
return null;
}
}

public Map<String, WebSocketSession> getAllUsers() {
return users;
}
}

4.建立配置類   WebSocketInterceptor

 

public class WebSocketInterceptor implements HandshakeInterceptor {

//在握手以前執行該方法, 繼續握手返回true, 中斷握手返回false. 經過attributes參數設置WebSocketSession的屬性
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
String ID = request.getURI().toString().split("ID=")[1];
//使用URLDecoder進行解碼,由於前段傳來的就是亂碼
String decode = URLDecoder.decode(ID, "UTF-8");
System.out.println("當前session的ID=" + decode);
//ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
//HttpSession session = serverHttpRequest.getServletRequest().getSession();
attributes.put("WEBSOCKET_USERID", decode);
}
return true;
}

//完成握手以後執行該方法
@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
System.out.println("進來webSocket的afterHandshake攔截器!");
}
}

5.jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><!DOCTYPE html><html><head>    <title>socket.html</title>    <meta name="keywords" content="keyword1,keyword2,keyword3">    <meta name="description" content="this is my page">    <%--<meta name="content-type" content="text/html" charset="UTF-8">--%>    <%--<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">--%>    <!--<link rel="stylesheet" type="text/css" href="./styles.css">--></head><body>Welcome<br/><input id='ipt' type='text' name="註冊"/><button onclick="getVal()">註冊</button><br><input id="text" type="text"/><button onclick="">發送的內容</button><br><input id='ipts' type='text' name="發給誰"/><button onclick="send()">發給誰</button><button onclick="closeWebSocket()">斷開鏈接</button></div><!-- 公共JS --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="../webSocket/jquery.min.js"></script><script type="text/javascript">    var websocket = null;    function getVal() {        //建立WebSocket        connectWebSocket();    }    //強制關閉瀏覽器  調用websocket.close(),進行正常關閉    window.onunload = function () {        //關閉鏈接        closeWebSocket();    }    //創建WebSocket鏈接    function connectWebSocket() {        var user = document.getElementById('ipt');//找到id是ipt的input節點;        var userID = user.value;        // alert(userID);        console.log("開始...");        //創建webSocket鏈接        websocket = new WebSocket("ws://192.168.1.46:9999/myHandler/ID=" + userID);        // websocket = new WebSocket("ws://94.191.34.57:9999/myHandler/ID=" + userID);        //打開webSokcet鏈接時,回調該函數        websocket.onopen = function () {            console.log("onpen");        }        //關閉webSocket鏈接時,回調該函數        websocket.onclose = function () {            //關閉鏈接            console.log("onclose");        }        //接收信息        websocket.onmessage = function (msg) {            console.log("receive msg");            console.log(msg.data);            alert(msg.data)        }    }    //發送消息    function send() {        var user = document.getElementById('ipts');//找到id是ipt的input節點;        var userID = user.value;        // alert(userID);        var postValue = {};        postValue.id = userID;        postValue.message = $("#text").val();        websocket.send(JSON.stringify(postValue));    }    //關閉鏈接    function closeWebSocket() {        if (websocket != null) {            websocket.close();        }    }</script><script type="text/javascript" charset="UTF-8"></script></body></html>
相關文章
相關標籤/搜索