java springboot整合websocket

2 篇文章 0 订阅
1 篇文章 0 订阅

介绍最简单的websocket使用
以及记录一下我使用springboot整合websocket遇到的一些问题

网上有很多demo,下面推荐一个最简单的,方便大家理解:
只需要处理1个HTML文件+1个pom文件+2个JAVA文件

一、Socket简介
Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求。Socket的英文原义是“孔”或“插座”,作为UNIX的进程通信机制。Socket可以实现应用程序间网络通信。
在这里插入图片描述
其余的一些想它为什么会出现,以及他和我们常用的http协议之间的区别等等,自己百度吧,网上有很多资料,这里我们就不浪费时间了,直接撸代码:

客户端代码 :↓↓

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <style>
        #message{
            height: 520px;
            border-bottom: 1px solid gray;
            padding: 20px 30px;
        }
        #container{
            margin: 0 auto;
            width: 720px;
            border: 1px solid gray
        }
        input{
            width: 300px;
            height: 36px;
            border: 1px solid gray;
            background:none;
            outline:none;
        }
        input:focus{
            border-color: yellow;
        }
        button{
            height: 36px;
        }
    </style>
</head>
<body>
<div id="container">
    <div id="message">

    </div>
    <div>
        <input id="text" type="text" placeholder="输入内容..."/>
        <button onclick="send()">发送消息</button>
    </div>
</div>
<script th:inline="javascript" type="text/javascript">
    var websocket = null;

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

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var data = event.data;
        document.getElementById('message').innerHTML += data+'<br/>';
    }

    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("onopen...");
    }
    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("onclose...");
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        console.log("onerror...");
    };
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

</script>
</body>
</html>

上面选择使用HTML而不用jsp,是因为html方便我们训练,
可以直接打开前端页面,而不用编写后端跳转代码。

后端代码:↓↓

package com.example.testwebsocket.controller.socket;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

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

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/myWebSocket")
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        //群发消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        message = this.session.getId() +":"+ message;
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}



如果不使用springboot的内置tomcat启动项目,则不需要这个配置类↓↓

package com.example.testwebsocket.controller.socket;

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


@Configuration
public class WebConfig {
    /**
     * 支持websocket
     * 如果不使用内置tomcat,则无需配置
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

pom文件加上websocket的包,并使用把springboot内置tomcat的websocket包忽略,就可以解决包冲突的问题了:↓↓

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>tomcat-embed-websocket</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

上面代码已经满足了实现浏览器和后端的链接和通信、关于如何巧用,大家可以再去研究;下面我们来看一下效果↓↓

项目启动成功
在这里插入图片描述
下面来打开一个客户端
在这里插入图片描述
在这里插入图片描述|因为后端代码onMessage方法里写了一个群发功能,所以我们可以把他看成一个群。我们再打开一个客户端进行连接,进行对话

在这里插入图片描述

在这里插入图片描述
|
|

访问流程图:

(下图代码与以上代码无关,主要用理解websocke的访问流程
附上以下demo代码连接:https://www.52pojie.cn/thread-995054-1-1.html)
在这里插入图片描述
在这里插入图片描述

总结一下

我遇到的难点主要在于websocket包与内置tomcat里的websocket包冲突了,起初找了一些文章,说是与内置tomcat的包冲突了,有各种各样的解决方法,但都解决不了。最后想到忽略掉tomcat的websocket包,我就是用这个方法解决的。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Boot整合WebSocket,你需要进行以下步骤: 1. 首先,在pom.xml文件中添加WebSocket的相关依赖。可以使用以下两个依赖之一: - 从中提到的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` - 从中提到的依赖: ```xml <!--webSocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类,这个类负责配置WebSocket的相关信息。你可以按照以下方式创建一个配置类[3]: ```java package com.loit.park.common.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` 3. 至此,你已经完成了WebSocket整合配置。现在,你可以在你的应用中创建WebSocket的控制器并定义你的WebSocket端点。你可以根据你的需求来实现WebSocket端点的业务逻辑。 这就是Spring Boot整合WebSocket的基本步骤。通过这种方式,你可以在Spring Boot应用中轻松地使用WebSocket进行实时通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合websocket](https://blog.csdn.net/weixin_45390688/article/details/120448778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot整合websocket(详解、教程、代码)](https://blog.csdn.net/hjq_ku/article/details/127503180)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值