前端vue后端springboot使用websocket的简单案例

前端使用vue,后端使用springboot。
前端和后端还使用了websocket连接,后端定时器发送数据给前端,前端使用echarts的插件进行柱状图显示。后端发送的值一直在变化,前端的柱状图也一直在变。

前端vue后端springboot使用websocket的简单案例_第1张图片
前端vue代码

<template>
    <div >
      <el-form ref="loginForm"  :model="loginForm" class = "loginContainer">
        <h3 class = "loginTitle">系统登录h3>
        <el-form-item>
          <el-input type="text" v-model="loginForm.username" placeholder="请输入用户名">el-input>
        el-form-item>
        <el-form-item>
          <el-input type="passward" v-model="loginForm.password" auto-complete="false" placeholder="请输入
密码" >el-input>
        el-form-item>
        <el-form-item>
          <el-input type="text" v-model="loginForm.code" placeholder="更换验证码" style="width: 250px">el-input>
          <img src="">
          <el-checkbox v-model="checked">rememberel-checkbox>
          <el-button type="primary" style="width: 100%" @click = "submitLogin" >登录el-button>
          <el-button type="primary" style="width: 100%" >打开el-button>
          <el-button type="primary" style="width: 100%" >发送el-button>
        el-form-item>
        <el-table
            :data="tableData"
            style="width: 100%">
          <el-table-column
              prop="x1"
              label="x轴"
              width="180">
          el-table-column>
          <el-table-column
              prop="y1"
              label="y轴"
              width="180">
          el-table-column>
        el-table>
      el-form>
      <div id = "mychartshow" style="width: 50%; height:500px">

      div>
    div>

template>

<script>
import * as echarts from 'echarts';
import axios from "axios"
const ws = new WebSocket('ws://127.0.0.1:8888/webSocket/111');
//echarts.init(document.getElementById('mychartshow')).dispose();


export default {
name: "Login",
  data(){
         return{
           captchaUrl:'',
           loginForm:{
             username:'admin',
             password:'123',
             code:'',
           },
           checked: true,
           tableData:[{
             x1:'10',
             y1:'20',
           }],
           chart: "",
           option :{
             title: {
               text: 'echarts 示例',
             },
             tooltip:{
               show:true,
             },
             xAxis:{
               type: 'category',
               data:['衬衫','羊毛衫']
             },
             yAxis:{
               type: 'value',
             },
             series:[
               {
                 name:'销量',
                 type:'bar',
                 data: [10,20],
                 itemStyle: {
                   normal:{
                     label:{
                       show:true,
                       position: 'top',
                       textStyle:{
                         color:'black',
                         fontsize:16,
                       }
                     }
                   }
                 }
               }
             ]

           }

         }
  },
  mounted() {
    ws.addEventListener('open',this.handleWsOpen.bind(this),false);
    ws.addEventListener('close',this.handleWsClose.bind(this),false);
    ws.addEventListener('error',this.handleWsError.bind(this),false);
    ws.addEventListener('message',this.handleWsMessage.bind(this),false);

  },
  methods:{
  init(){



  },
    submitLogin(){
          axios.get('/index').then(res=>{
            alert(JSON.stringify(res.data));

          })
          this.$router.push('/sellerpage')
    },
    handleWsOpen(e){
        console.log('FE: WebSocket open',e);
    },
    handleWsClose(e){
      console.log('FE: WebSocket close',e);
    },
    handleWsError(e){
      console.log('FE: WebSocket error',e);
    },
    handleWsMessage(e){
      let datavalue = JSON.parse(e.data);
      this.tableData[0].x1 = datavalue.x1;
      this.tableData[0].y1 = datavalue.y1;
      this.option.series[0].data[0] = datavalue.x1;
      this.option.series[0].data[1] = datavalue.y1;
      var myChart = echarts.init(document.getElementById('mychartshow'));
      myChart.setOption(this.option);
      console.log(this.option)
      console.log('FE: WebSocket message',e);
    }

  }
}
script>

<style >
.loginContainer{
  border-radius: 15px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 15px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: aquamarine;
}
.loginTitle{
  text-align: center;
}
style>
vue..config.js
配置文件内容

```javascript
module.exports = {
    //axios域代理,解决axios跨域问题
    publicPath: './',
}

主要解决打包时找不到路径问题
Java代码

package com.example.demo.config;

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();
    }
}
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.example.demo.service.WebSocketServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Controller
public class WebSocketController {
    @Autowired
    private WebSocketServer webSocketServer;

    @RequestMapping("/index1")
    public String index() {
        return "index1";
    }

    @GetMapping("/webSocket")
    public ModelAndView socket() {
        ModelAndView mav=new ModelAndView("/webSocket");
//        mav.addObject("userId", userId);
        return mav;
    }


}
package com.example.demo.service;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

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

import org.springframework.stereotype.Component;


/**
 * 发送消息的类
 */

@Component
@ServerEndpoint(value = "/webSocket/{sid}")
public class WebSocketServer {

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();


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

    //接收sid
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到来自窗口"+sid+"的信息:"+message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
          System.out.println("error");
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
```java
    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
        //System.out.println("推送消息到窗口"+sid+",推送内容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if(sid==null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }
    public static void sendAllMessage(String message) {
        try {
            for (WebSocketServer item : webSocketSet) {
                item.sendMessage(message);
            }
        } catch (Exception e) {
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
定时器
package com.example.demo.util;

import com.example.demo.service.UdpIntegrationClient;
import com.example.demo.service.WebSocketServer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class time {
    private int value = 0;
    private int value2 = 2;
    @Autowired
    private UdpIntegrationClient udpIntegrationClient;
    @Scheduled(fixedRate = 3000)
    public void testTask(){
        //System.out.println("定时器启动");
        try
        {
            WebSocketServer.sendInfo(numbers(),"111");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    public String numbers(){
        value += 1;
        value2 += 1;
        JSONObject object = new JSONObject();
        try {
            object.put("x1", value*value);
            object.put("y1",value2 * 2);
        }catch (JSONException e)
        {
            e.printStackTrace();
        }
        return object.toString();

    }

}
主程序
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

你可能感兴趣的:(前端,vue.js,后端)