springboot+websocket+vue

£可爱£侵袭症+ 提交于 2020-02-29 04:32:53

一 后端

1. pom.xml中引入依赖

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

2. 写一个websocket配置类

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

3. 写一个websocket工具类

@Component
@ServerEndpoint("/socket")
public class WebSocketServer {
    /**
     * 全部在线会话
     */
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();


    /**
     * 当客户端打开连接:1.添加会话对象 2.更新在线人数
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineSessions.put(session.getId(), session);

    }

    /**
     * 当客户端发送消息:1.获取它的用户名和消息 2.发送消息给所有人
     * <p>
     * PS: 这里约定传递的消息为JSON字符串 方便传递更多参数!
     */
    @OnMessage
    public void onMessage(Session session, String jsonStr) {
        System.out.println("jsonStr========>" + jsonStr);
    }

    /**
     * 当关闭连接:1.移除会话对象 2.更新在线人数
     */
    @OnClose
    public void onClose(Session session) {
        onlineSessions.remove(session.getId());

    }

    /**
     * 当通信发生异常:打印错误日志
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 公共方法:发送信息给所有人
     */
    public void sendMessageToAll(String jsonMsg) {
        onlineSessions.forEach((id, session) -> {
            try {
                session.getBasicRemote().sendText(jsonMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}

4.如何调用?

@Autowired
WebSocketServer webSocketServer;

webSocketServer.sendMessageToAll("json");

二 前端

data () {
  return {
    websock:null
  }
},
created () {
  this.initWebSocket();
},
methods: {
initWebSocket () { //初始化weosocket
constwsuri = "ws://127.0.0.1:8080/erp-web/socket";
this.websock = newWebSocket(wsuri);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},

websocketonopen(){ //连接建立之后执行send方法发送数据
  letactions = {"test":"12345"};
  this.websocketsend(JSON.stringify(actions));
},

websocketonerror(){//连接建立失败重连
  this.initWebSocket(); 
},

websocketonmessage(e){ //数据接收
  console.log("data:",e.data)
// const redata = JSON.parse(e.data);
},

websocketsend(Data){//数据发送
  this.websock.send(Data);
},

websocketclose(e){  //关闭
  console.log('断开连接',e);
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!