1、對websocket的認(rèn)識(shí)
實(shí)時(shí)性蛙埂、雙工通信、走websocket(ws)協(xié)議不是HTTP遮糖、“拉和推”的概念绣的,股票、石墨文檔多方在線協(xié)作欲账、智能家居屡江、賽況更新
2、什么是websocket
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議赛不。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信——允許服務(wù)器主動(dòng)發(fā)送信息給客戶端惩嘉。
websocket.png
3、為什么需要websocket
我們已經(jīng)有了 HTTP 協(xié)議踢故,為什么還需要另一個(gè)協(xié)議文黎?它能帶來什么好處?
- 答案很簡單殿较,因?yàn)?HTTP 協(xié)議有一個(gè)缺陷:通信只能由客戶端發(fā)起耸峭,HTTP 協(xié)議做不到服務(wù)器主動(dòng)向客戶端推送信息。
舉例來說淋纲,我們想要查詢當(dāng)前的排隊(duì)情況劳闹,只能是頁面輪詢向服務(wù)器發(fā)出請求,服務(wù)器返回查詢結(jié)果洽瞬。輪詢的效率低本涕,非常浪費(fèi)資源(因?yàn)楸仨毑煌_B接,或者 HTTP 連接始終打開)伙窃。因此WebSocket 就是這樣發(fā)明的菩颖。
4、SpringBoot2對WebSocket的支持很贊
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
5对供、WebSocketConfig
package com.springboot.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 開啟WebSocket支持
*
* @author Moqi
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
6位他、WebSocketServer
package com.springboot.websocket.config;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
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 org.springframework.stereotype.Component;
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
//靜態(tài)變量氛濒,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的鹅髓。
private static int onlineCount = 0;
//concurrent包的線程安全Set舞竿,用來存放每個(gè)客戶端對應(yīng)的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個(gè)客戶端的連接會(huì)話窿冯,需要通過它來給客戶端發(fā)送數(shù)據(jù)
private Session session;
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數(shù)加1
System.out.println("有新窗口開始監(jiān)聽,當(dāng)前在線人數(shù)為" + getOnlineCount());
try {
sendMessage("連接成功");
} catch (IOException e) {
System.out.println("WebSocket IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減1
System.out.println("有連接關(guān)閉骗奖!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到客戶端的信息:" + message);
//群發(fā)消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("發(fā)生錯(cuò)誤");
error.printStackTrace();
}
/**
* 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群發(fā)自定義消息
*/
public static void sendInfo(String message) throws IOException {
System.out.println("推送消息內(nèi)容:" + 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--;
}
}
7、WebSocketController
package com.springboot.websocket.controller;
import com.springboot.websocket.config.WebSocketServer;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
public class WebSocketController {
//推送數(shù)據(jù)接口 @RequestMapping("/socket/push")
public String pushMsg(String message) {
try {
WebSocketServer.sendInfo(message);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
8醒串、index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<h2>WebSocket</h2>
<script>
var socket;
if (typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
} else {
console.log("您的瀏覽器支持WebSocket");
//實(shí)現(xiàn)化WebSocket對象执桌,指定要連接的服務(wù)器地址與端口建立連接
socket = new WebSocket("ws://localhost:8080/websocket");
//打開事件
socket.onopen = function () {
console.log("Socket已打開");
socket.send("這是來自客戶端的消息:" + new Date());
};
//獲得消息事件
socket.onmessage = function (msg) {
console.log(msg);
alert(msg);
};
//關(guān)閉事件
socket.onclose = function () {
console.log("Socket已關(guān)閉");
};
//發(fā)生了錯(cuò)誤事件
socket.onerror = function () {
alert("Socket發(fā)生了錯(cuò)誤");
}
}
</script>
</body>
</html>
截圖.png