Springboot(四)使用WebSocket

WebSocket

  • webSocket用于页面与逻辑代码的消息传递,且连接是全双工通信。
  • pom.xml文件中引入spring-boot-starter-websocket依赖。
  • 在需要进行消息展示的页面插入以下代码。
  • 一般页面使用modal组件显示消息内容。
<script>

        if('WebSocket' in window){
            
            //链接地址
            var websocket=new WebSocket("ws://localhost:8080/sell/websocket");

            websocket.onopen=function (ev) {
                console.log("建立websocket链接");
            }

            websocket.onclose=function (ev) {
                console.log("连接取消");
            }

            websocket.onmessage=function (ev) {
                console.log("获取信息:" + ev.data);
                $('#messageModal').html(ev.data);
                $('#myModal').modal('show');
                document.getElementById('message_mp3').play();
                console.log("发送消息");
            }

            websocket.onbeforeunload=function (ev) {
                console.log("链接建立之前先关闭之前的链接");
            }

        }else{
            alert("您的浏览器不支持WebSocket");
        }

</script>
  • 在逻辑代码部分,创建接收页面传递过来的请求服务;
/**
 * websocket配置类  注入对象
 */
@Component
public class WebSocketConfig {

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


/**
 * 消息服务
 */
@Component
@ServerEndpoint("/websocket")//访问路径
public class WebSocketService {

    private Session session;//一次会话

    //用于接收所有的链接请求
    private static CopyOnWriteArraySet<WebSocketService> webSockets=new CopyOnWriteArraySet<WebSocketService>();

    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSockets.add(this);//请求接收同时建立链接,将当前WebSocketService加入集合
    }

    @OnClose
    public void onClose(){
        webSockets.remove(this);//取消链接,将当前WebSocketService移出集合
    }

    @OnMessage
    public void onMessage(String message){
        System.out.println(message);//消息获取
    }

    /**
     * 发送消息给页面
     * @param message
     */
    public void sendMessage(String message){
        //广播发送消息
        for(WebSocketService webSocketService:webSockets){
            try {
                webSocketService.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
  • 在需要进行消息通信的地方调用WebSocketService类的sendMessage方法即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot项目中使用WebSocket,首先需要引入spring-boot-starter-websocket组件。这可以通过在pom.xml文件中添加以下依赖实现: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 然后,你需要在你的项目中创建一个WebSocket处理器类。这个处理器类应该使用注解@Component进行声明,以便被Spring管理。在处理器类中,你可以定义处理WebSocket连接、消息发送和接收的方法。 在前端代码中,你需要确保WebSocket地址与后端的地址一致。例如,可以使用以下代码创建WebSocket: ```javascript websocket = new WebSocket("ws://localhost:8080/websocket"); ``` 通过上述步骤,你就可以在Spring Boot中成功使用WebSocket了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [WebsocketSpringboot使用](https://blog.csdn.net/u011144425/article/details/79231212)[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%"] - *3* [springboot使用websocket](https://blog.csdn.net/qq_36027670/article/details/83009586)[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、付费专栏及课程。

余额充值