springBoot2.0+vue实现websocket通信【最新,亲测有效】

news/2024/7/10 2:40:51 标签: springboot, vue, websocket, java, 小道仙

先来看下效果,如果是你想要的效果就继续往下面看

在这里插入图片描述


如果你只是单纯的想使用前端或者后端也是可以的

vue_4">前端:vue

<template>    
	<div>       
		<h1>测试webSocket</h1>      
		<button @click="getWebsocket">点击请求后台数据</button>    
	</div>    
</template>
<script>
export default {        
	created() { // 页面创建生命周期函数              
		this.initWebSocket()        
	},        
	destroyed: function () { // 离开页面生命周期函数              
		this.websocketclose();        
	},        
	methods: {            
		initWebSocket: function () {                
			// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https                
			this.websock = new WebSocket("ws://localhost:8185/api/websocket/DPS007");                
			this.websock.onopen = this.websocketonopen;                
			this.websock.onerror = this.websocketonerror;                
			this.websock.onmessage = this.websocketonmessage;                
			this.websock.onclose = this.websocketclose;              
		},              
		websocketonopen: function () {                
			console.log("WebSocket连接成功");              
		},              
		websocketonerror: function (e) {                
			console.log("WebSocket连接发生错误");              
		},              
		websocketonmessage: function (e) {                
			console.log(e.data);                // console.log(e);              
		},              
		websocketclose: function (e) {                
			console.log("connection closed (" + e.code + ")");              
		},              
		getWebsocket:function(){                l
			et url = "http://localhost:8185/api/teachStf/import?shipId=DPS007"                
			// 这里只是一个基于axios的ajax请求,你可以换成你的请求格式                
			this.$ajax.get(url)              
		}       
	 }    
}
</script>
<style lang="less" scoped>
</style>


在这里插入图片描述


java_58">后端:java

1、WebSocketConfig
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();
   }
}
2、WebSocket
package com.xdx97.party.common.config;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{shopId}")
//此注解相当于设置访问URL
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="shopId")String shopId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(shopId, session);
        System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for(WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息 (发送文本)
    public void sendTextMessage(String shopId, String message) {
        Session session = sessionPool.get(shopId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息 (发送对象)
    public void sendObjMessage(String shopId, Object message) {
        Session session = sessionPool.get(shopId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendObject(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

3、测试

你后台写一个请求的方法,把下面代码放进去就好了

for (int i = 0; i < 10; i++){
    Thread.sleep(1000);
    webSocket.sendTextMessage(shipId, ""+i);
}

并且注入webSocket

@Autowired
private WebSocket webSocket;

给你看看我的方法做参考
在这里插入图片描述
在这里插入图片描述

鉴于有几个小伙伴需要源码,我又重新写了这个demo,获取方式关注公众号后台回复:WebSocketDemo

各位老哥,如果对你有帮助,关注后可否不取消。
在这里插入图片描述


http://www.niftyadmin.cn/n/775139.html

相关文章

随机句子我在人间凑数的日子V1.2成品源码+API

介绍&#xff1a; 响应式界面&#xff0c;简洁大方是从一个博客上面扒的&#xff0c;改成了我在人间凑数的日子随机句子 源码上传到虚拟主机即可使用&#xff0c;如果需要使用自己本地API就需要服务器支持PHP API和程序一同打包&#xff0c;获取文案地址大约在index.html的96行…

利用python顶点书包爬虫小说附带源码

介绍&#xff1a; PYTHON爬虫代码闲来无事用Python的scrapy框架练练手&#xff0c;爬取顶点小说网的所有小说的详细信息。 -小K娱乐网注重分享&#xff0c;免费分享压缩包里面附带了python爬虫源码&#xff0c;有兴趣的朋友还可以自己多多研究哈升级下 网盘下载地址&#xff1…

phpStudy发布多个web项目

目的&#xff1a;使用phpStudy发布多个web项目 第一步&#xff1a;修改httpd.conf 第二步&#xff1a;把你的多个项目放好 第三步&#xff1a;配置vhost.conf

最新emlog程序网站公告栏插件修复多功能版

介绍&#xff1a; Emlog插件兼容5.3.1稳定版6.0版本不兼容可以在首页或者底部显示一个版透明的网站公告栏&#xff0c;可以自定义公告内容&#xff0c;Emlog插件不错&#xff0c;直接在后台上传即可激活使用。 网盘下载地址&#xff1a; https://zijiewangpan.com/TazOOJAKFB…

-source 1.5 中不支持静态接口方法调用【终极版解决idea版】

很明显就是说版本不对要用7以上。下面给出两种办法&#xff0c;第一种无效再使用第二种 第一种 第一步 第二步&#xff1a; 如果这还没有解决请使用第二种方法 第二种 把下面的代码copy到你的父工程的pom.xml里面 <build><plugins><plugin><groupId&g…

最新智云全能API接口PHP源码

介绍&#xff1a; 源码直接上传即可访问&#xff0c;无需数据库&#xff0c;不支持上传二级目录访问&#xff01; 源码上传后请访问&#xff1a;你的域名/inde.html&#xff08;可以将inde.html重新修改其他名称访问&#xff09; 解析接口文件&#xff08;api&#xff09;文件…

最新Emlog网址目录技术导航网模板源码

介绍&#xff1a; Emlog网址目录技术导航网模板&#xff0c;支持模板设置 自适应PC手机端 全站自适应支持多端&#xff0c;强大的插件功能&#xff0c;支持模板设置&#xff0c;带有三个广告位 网盘下载地址&#xff1a; https://zijiewangpan.com/KaeEGHNHVnQ 图片&#xff…

仿B站简单版播放器带有弹幕,并支持解析

介绍&#xff1a; 泛滥版公共弹幕库API:https://www.vivicms.cc/id/ 正式版公共弹幕库API:https://www.vivicms.cc/v3/ 网盘下载地址&#xff1a; https://zijiewangpan.com/aLjYbf1A0tu 图片&#xff1a;