电光石火-穿越时空电光石火-穿越时空


springboot vue整合websocket

1.引入包

compile 'org.springframework.boot:spring-boot-starter-websocket'

2.新建类MyWebsocket

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebsocket {

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebsocket> webSocketSet = new CopyOnWriteArraySet<MyWebsocket>();

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

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接成功");
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("success");
            System.out.println("发送连接成功");
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

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

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

    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebsocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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


    public void sendMessage(String message) throws IOException {
        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--;
    }

}

3.调用接口MyWebsocket.sendInfo("notice");

4.vue代码

 methods:{
      websocket () {
        let ws = new WebSocket('ws://192.168.1.205:9032/websocket');
        ws.onopen = () => {
          // Web Socket 已连接上,使用 send() 方法发送数据
          //console.log('数据发送中...')
          //ws.send('Holle')
          //console.log('数据发送完成')
        }
        ws.onmessage = evt => {
          console.log('数据已接收...')
          var received_msg = evt.data;
          console.log(received_msg);

          if("notice" == received_msg)
          {
            this.initData();
            this.play();
          }
          else{
            console.log("不刷新");
          }
        }
       /* ws.onclose = function () {
          // 关闭 websocket
          console.log('连接已关闭...')
        }
        // 路由跳转时结束websocket链接
        this.$router.afterEach(function () {
          ws.close()
        })*/
      },
}
本博客所有文章如无特别注明均为原创。作者:似水的流年
版权所有:《电光石火-穿越时空》 => springboot vue整合websocket
本文地址:http://www.ilkhome.cn/index.php/archives/343/
欢迎转载!复制或转载请以超链接形式注明,文章为 似水的流年 原创,并注明原文地址 springboot vue整合websocket,谢谢。

评论

  1. 1111显示

    11 2018-12-17    回复