Spring Boot 使用websocket
1.搭建Spring Boot項目 wsdemo
1.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sunlong</groupId>
<artifactId>spring-boot-websocket-demo</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>spring-boot-websocket-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2 建立WebSocket接口 MyWebSocket.java
package com.sunlong.websocket;
import com.sunlong.service.SendService;
import com.sunlong.utils.SpringUtil;
import org.springframework.stereotype.Controller;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
/**
* spring-boot-websocket-demo
*
* @Author 孫龍
* @Date 2017/12/4
*/
@ServerEndpoint(value = "/websocket")
@Controller
public class MyWebSocket {
//靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)笤喳。
private static int onlineCount = 0;
//注入Service只能使用這種方式
private SendService sendService = SpringUtil.getBean(SendService.class);
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) {
addOnlineCount(); //在線數(shù)加1
System.out.println("有新連接加入谤专!ID是" + session.getId() + " 當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose(Session session) {
subOnlineCount(); //在線數(shù)減1
System.out.println("有一連接關(guān)閉揽祥!ID是:" + session.getId() + " 當(dāng)前在線人數(shù)為" + getOnlineCount());
try {
session.close();
} catch (IOException e) {
System.out.println("關(guān)閉資源時出錯!");
e.printStackTrace();
}
}
/**
* 收到客戶端消息后調(diào)用的方法
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("來自客戶端的消息:" + message + " ID是:" + session.getId());
sendService.sendMessage(session, "服務(wù)器消息!");
}
/**
* 發(fā)生錯誤時調(diào)用
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("發(fā)生錯誤》》發(fā)生時間:" + System.currentTimeMillis() + " ID是:" + session.getId());
error.printStackTrace();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
1.3發(fā)送消息的Service
接口 SendService.java
package com.sunlong.service;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
/**
* spring-boot-websocket-demo
*
* @Author 孫龍
* @Date 2017/11/28
*/
public interface SendService {
/**
* 給多個用戶發(fā)送數(shù)據(jù)
*
* @param sessionList
* @param message
* @throws IOException
*/
void sendBatch(List<Session> sessionList, String message) throws IOException;
/**
* 發(fā)送消息
*
* @param session
* @param message
* @throws IOException
*/
void sendMessage(Session session, String message) throws IOException;
}
實現(xiàn)類 SendServiceImpl.java
package com.sunlong.service.impl;
import com.sunlong.service.SendService;
import org.springframework.stereotype.Service;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
/**
* spring-boot-websocket-demo
*
* @Author 孫龍
* @Date 2017/11/28
*/
@Service
public class SendServiceImpl implements SendService {
@Override
public void sendBatch(List<Session> sessionList, String message) throws IOException {
for (Session session : sessionList) {
sendMessage(session, message);
}
}
@Override
public void sendMessage(Session session, String message) throws IOException {
session.getBasicRemote().sendText(message);
}
}
1.4獲取Spring容器Bean的SpringUtil.java
package com.topsec.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
// 獲取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通過name獲取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
// 通過class獲取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
// 通過name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
}
1.5前端訪問頁面 ws01.html
在resources/templates目錄下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text"/>
<button onclick="send()">發(fā)送</button>
<button onclick="closeWebSocket()">關(guān)閉連接</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
var host = "";
if (window.location.protocol == 'http:') {
host = 'ws://localhost:8585/websocket';
} else {
host = 'wss://localhost:8585/websocket';
}
//判斷當(dāng)前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket(host);
} else {
alert("該瀏覽器不支持WebSocket重荠!");
// return;
}
//連接發(fā)生錯誤的回調(diào)方法
websocket.onerror = function () {
setMessageInnerHTML("連接出錯");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function (event) {
console.log("連接成功");
setMessageInnerHTML("已連接服務(wù)器!");
}
//接收到消息的回調(diào)方法
websocket.onmessage = function (event) {
console.log(event.data);
setMessageInnerHTML(event.data);
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function () {
setMessageInnerHTML("連接關(guān)閉");
}
//監(jiān)聽窗口關(guān)閉事件虚茶,當(dāng)窗口關(guān)閉時戈鲁,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口媳危,server端會拋異常荞彼。
window.onbeforeunload = function () {
websocket.close();
}
//將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關(guān)閉連接
function closeWebSocket() {
websocket.close();
}
//發(fā)送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
1.6 配置頁面映射路徑 WebMvcConfig.java
package com.sunlong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* spring-boot-websocket-demo
* 該類的作用是可以為ws.html提供便捷的地址映射,只需要在地址欄里面輸入localhost:8080/ws,就會找到ws.html
*
* @Author 孫龍
* @Date 2017/11/28
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ws01").setViewName("/ws01");
}
/**
* 配置Spring支持的websocket的類,是必須的
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
1.7 端口配置 application.yml
server:
port: 8585
1.8 啟動類WsdemoApplication.java
package com.topsec;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WsdemoApplication {
public static void main(String[] args) {
SpringApplication.run(WsdemoApplication.class, args);
}
}
1.9 啟動
啟動項目待笑,打開瀏覽器訪問http://localhost:8585/ws01 給websocket發(fā)送消息鸣皂,測試是否成功;
Github代碼示例
希望能夠幫助到你暮蹂,幫到你請給我一個星星寞缝!