Vue+Springboot前后端分离websocket的使用

为什么80%的码农都做不了架构师?>>>   hot3.png

Springboot:

113536_qG33_2733866.png

MyWebsocket.java

package com.oppo.tcms.socket;


import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/***
 *
 * Created by 80071482 on 2018/2/23.
 * Author (Bony)
 ***/
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebsocket {

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        System.out.println("有一连接关闭");
    }

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

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


}

myWebSocketConfig.java

package com.oppo.tcms.socket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/***
 *
 * Created by 80071482 on 2018/2/23.
 * Author Zhangboyi (Bony)
 ***/


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

}

VUEJS:


            websocket () {
                let ws = new WebSocket('ws://172.17.127.164:8000/websocket');
                ws.onopen = () => {
                    // Web Socket 已连接上,使用 send() 方法发送数据
                    console.log('数据发送中...')
                    ws.send('Holle')
                    console.log('数据发送完成')
                }
                ws.onmessage = evt => {
                     console.log('数据已接收...')
                }
                ws.onclose = function () {
                    // 关闭 websocket
                    console.log('连接已关闭...')
                }
                // 路由跳转时结束websocket链接
                this.$router.afterEach(function () {
                    ws.close()
                })
            }

 

转载于:https://my.oschina.net/hibony/blog/1623339

你可能感兴趣的:(Vue+Springboot前后端分离websocket的使用)