Spring Boot 使用websocket(Spring支持的原生方式)

Spring Boot 使用websocket

1.搭建Spring Boot項(xiàng)目 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)閉資源時(shí)出錯(cuò)!");
            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ā)生錯(cuò)誤時(shí)調(diào)用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("發(fā)生錯(cuò)誤》》發(fā)生時(shí)間:" + 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 {

    /**
     * 給多個(gè)用戶發(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;
}

實(shí)現(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ā)生錯(cuò)誤的回調(diào)方法
    websocket.onerror = function () {
        setMessageInnerHTML("連接出錯(cuò)");
    };

    //連接成功建立的回調(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)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。
    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,就會(huì)找到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 啟動(dòng)類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 啟動(dòng)

啟動(dòng)項(xiàng)目,打開瀏覽器訪問http://localhost:8585/ws01 給websocket發(fā)送消息,測試是否成功;

Github代碼示例
希望能夠幫助到你,幫到你請給我一個(gè)星星!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,261評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,534評論 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,939評論 1 92
  • 此篇翻譯的是Spring Boot官方指南 Part III. 使用 Spring Boot (Using Spr...
    K天道酬勤閱讀 6,942評論 0 21
  • 不領(lǐng)情小姐有些瘋狂,有些特立獨(dú)行。 當(dāng)我們還在教室乖乖上自習(xí),期末眼巴巴盼著老師圈重點(diǎn)的時(shí)候,她早就把成都大街小巷...
    鳴空閱讀 366評論 0 4

友情鏈接更多精彩內(nèi)容