1 簡(jiǎn)介
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信。Websocket可以讓服務(wù)器端主動(dòng)推送消息數(shù)據(jù)給到瀏覽器客戶端,以達(dá)到可以實(shí)時(shí)交互的目的,是一種非常實(shí)用的實(shí)時(shí)推送技術(shù)。
2 pom文件添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
3 創(chuàng)建 WebSocketConfig
啟用WebSocket的支持
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 開啟WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4 創(chuàng)建 WebSocketServer
因?yàn)閃ebSocket是類似客戶端服務(wù)端的形式(采用ws協(xié)議),那么這里的WebSocketServer其實(shí)就相當(dāng)于一個(gè)ws協(xié)議的Controller直接@ServerEndpoint("/websocket") @Component啟用即可,然后在里面實(shí)現(xiàn)對(duì)應(yīng)的方法即可。
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
//靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
//與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
private Session session;
//接收sid
private String sid = "";
/**
* 連接建立成功調(diào)用的方法
* */
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數(shù)加1
log.info("有新窗口開始監(jiān)聽:" + sid + ",當(dāng)前在線人數(shù)為" + getOnlineCount());
this.sid = sid;
try {
sendMessage("連接成功");
} catch (IOException e) {
log.error("websocket IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減1
log.info("有一連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息
* */
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到來自窗口" + sid + "的信息:" + message);
//群發(fā)消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("發(fā)生錯(cuò)誤" + error.getMessage());
}
/**
* 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
*/
public void sendMessage(String message) throws IOException {
this.session.getAsyncRemote().sendText(message);
}
/**
* 群發(fā)自定義消息
* */
public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口" + sid + ",推送內(nèi)容:" + message);
for (WebSocketServer item : webSocketSet) {
try {
//這里可以設(shè)定只推送給這個(gè)sid的,為null則全部推送
if (sid == null) {
item.sendMessage(message);
} else if (item.sid.equals(sid)) {
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--;
}
}
5 測(cè)試
啟動(dòng)服務(wù),然后使用客戶端模擬測(cè)試,輸入以下鏈接地址:
ws://localhost:8280/websocket/user001

image.png
6 nginx 反向代理
一般為了便于管理URL,我們都會(huì)使用nginx代理ws,讓ws復(fù)用http的端口,即80端口
1)編輯nginx.conf,在http區(qū)域內(nèi)添加下面配置:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
2) location增加以下配置
# websocket
location ^~/websocket/{
rewrite ^/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:8280/;
proxy_set_header Host $host:$server_port;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
啟動(dòng)ngnix并驗(yàn)證,直接用域名即可,不需要再帶端口
ws://localhost/websocket/user001

image.png
7 wss配置
有了nginx反向代理,配置wss就和配置https一樣,直接到nginx的server里面增加SSL證書即可,這樣既配置了HTTPS也同時(shí)配置了WSS。
server {
listen 80;
listen 443 ssl;
server_name localhost;
ssl_certificate <*.pem文件路徑>;
ssl_certificate_key <*.key文件路徑>;
# websocket
location ^~/websocket/{
rewrite ^/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:9009/;
proxy_set_header Host $host:$server_port;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
8 資源
代碼示例請(qǐng)?jiān)L問:https://gitlab.com/feny-blog/springboot-websocket.git