001-WebSocket Java SpringBoot Simple Demo

工作需求,进行WebSocket通信,SpringBoot项目,但是网上查了,好多只写了个打了@ServerEndpoint注解的类,就能用了。但是我试了就是不行。后来查了资料,说是与使用的框架有关。那么我的环境是SpringBoot项目,基于这个环境,记录一下能运行起来的完整代码。

1,创建SpringBoot项目

主要添加spring-boot-starter-web依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

这个没什么说的,java人都知道。

2,添加WebSocket依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

3,编写Socket连接类

package org.tzl.message;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/*******************************************************
 * WebSocket连接
 *
 * @author: tzl
 * @time: 2022-01-06 20:05:54
 * *****************************************************/
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketMessage {

    public WebSocketMessage(){
        System.out.println("----------tzl----------");
    }

    // 打开连接
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("打开连接");
    }

    // 接收消息
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收消息:" + message);
    }

    // 连接错误
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("连接错误");
    }

    // 连接关闭
    @OnClose
    public void onClose() {
        System.out.println("连接关闭");
    }
}

客户端与服务端每创建一个连接,就是这样一个对象,那么把这些对象管理起来,通过标识标记好,就可以随意向其它客户端发消息了;

上述类有两个点需要注意:

  a.需要标注@ServerEndpoint(value = "/websocket")注解

  b.需要标注@Component注解

4,编写配置类

package org.tzl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/*******************************************************
 * WebSocket配置类 
 *
 * @author: tzl
 * @time: 2022-01-06 20:15:05
 * *****************************************************/
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

引用【https://www.cnblogs.com/javafucker/p/10249425.html】博主的话

如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理

解释我最初的疑问。

5,编写客户端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket消息测试</title>
</head>
<body>
<h3>WebSocket消息测试</h3><br/><br/>
<input id="text" type="text"/>
<button onclick="send()"> 发送</button>
<button onclick="closeWebSocket()">关闭</button><br/><br/>
<div id="message"></div>

<script type="text/javascript">
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket");
    } else {
        alert('浏览器不支持WebSocket');
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("连接出现错误");
    }

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML("连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("连接关闭");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</body>
</html>

6,运行效果

  a.客户端

  

 

   b.服务端

  

 

posted on 2022-01-08 21:09  走调的钢琴  阅读(67)  评论(0)    收藏  举报