博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring boot + Websocket
阅读量:6248 次
发布时间:2019-06-22

本文共 4138 字,大约阅读时间需要 13 分钟。

1、添加配置类

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configurationpublic class WebSocketConfig {     /**     * 注入ServerEndpointExporter,     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint     */    @Bean    public ServerEndpointExporter serverEndpointExporter() {        return new ServerEndpointExporter();    }}

2、添加WebSocket类

import org.slf4j.Logger;import org.slf4j.LoggerFactory;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}")public class WebSocket {    private static Logger logger = LoggerFactory.getLogger(WebSocket.class);    private Session session;    private static CopyOnWriteArraySet
webSockets = new CopyOnWriteArraySet<>(); private static Map
sessionPool = new HashMap<>(); @OnOpen public void onOpen(Session session, @PathParam(value = "shopId") String shopId) { this.session = session; webSockets.add(this); sessionPool.put(shopId, session); logger.info("有新的连接,总数为:{}", webSockets.size()); } @OnClose public void onClose() { webSockets.remove(this); logger.info("连接断开,总数为:{}", webSockets.size()); } @OnMessage public void onMessage(String message) { logger.info("收到客户端消息:{}", message); } // 此为广播消息 public void sendAllMessage(String message) { for (WebSocket webSocket : webSockets) { System.out.println("【websocket消息】广播消息:" + message); try { webSocket.session.getAsyncRemote().sendText(message); } catch (Exception e) { logger.error("", e); } } } // 此为单点消息 public void sendOneMessage(String shopId, String message) { Session session = sessionPool.get(shopId); if (session != null) { try { session.getAsyncRemote().sendText(message); } catch (Exception e) { logger.error("", e); } } }}

3、添加测试类

import com.sgcc.gtfsamservice.componet.WebSocket;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("api")public class TestController {    @Autowired    private WebSocket webSocket;    @RequestMapping("/sendAllWebSocket")    public String test() {            webSocket.sendAllMessage("hello");        return "多发!";            }    @RequestMapping("/sendOneWebSocket")    public String sendOneWebSocket() {        webSocket.sendOneMessage("channel001", "hello!");        return "单发";    }}

4、前端Vue

export default {    name: 'relationship',    data () {      return {      }    },    created () { // 页面创建生命周期函数      this.initWebSocket()    },    destroyed: function () { // 离开页面生命周期函数      this.websocketclose()    },    methods: {      initWebSocket: function () {        // ws等同http,wss等同https,其中ip为后端应用主机,port为后端启动所占用的端口        this.websock = new WebSocket('ws://ip:port/websocket/channel001')        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) {        var da = JSON.parse(e.data)        console.log(da)        this.message = da      },      websocketclose: function (e) {        console.log('connection closed (' + e.code + ')')      },

转载于:https://blog.51cto.com/handsomebingli/2370247

你可能感兴趣的文章
Java高级教程:Java并发性和多线程
查看>>
Android更新带进度条的通知栏
查看>>
Python XML解析
查看>>
五步搭建属于自己的个人网站
查看>>
换今日特价图片---轻开电子商务系统(企业入门级B2C站点)
查看>>
任务调度利器:Celery
查看>>
利用java mail发送邮件(转)
查看>>
Mybatis(六) Spring整合mybatis
查看>>
教您用Xshell快速连接远程电脑
查看>>
怎样阅读源码
查看>>
RxJava系列之中的一个 初识Rxjava
查看>>
智能巡检资料
查看>>
cocos2dx-3.1 接入多盟广告sdk+Android (2)
查看>>
Android Eclipse 导入 AS Gradle AAR 库手冊
查看>>
腾讯实习生三面
查看>>
CTFcrackTools-V3 - 一款旨在帮助 CTFer 在 CTF 中发挥作用的一个框架
查看>>
weblogic隐藏版本号教程(10.3.6为例)
查看>>
Html input 常见问题
查看>>
storm笔记:Storm+Kafka简单应用
查看>>
关于宽带接两台路由,并且第二台需要关闭DHCP的设置
查看>>