Websocket前后台交互

websocket前后台交互

前台页面vue

<template>
  <div class="hello">


    <h1 style="text-align:center;">欢迎来到人工智能管理系统</h1>


    <h3>实时监控</h3>
    <ul>
      <li>
        <!--<a
          href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel"
          target="_blank"
          rel="noopener"
          >babel</a
        >-->
          <el-button type="primary"  @click="onConfirm">socket<i class="el-icon-upload el-icon--right"></i></el-button>
      </li>

    </ul>

  </div>
</template>

<script>
export default {
  name: "HelloWorld",

  data () {
    return {
      path:"http://localhost:9588/link/test",
      socket:"",
      ws:'',
      receive:'',
      params:{
        paraName: 'admin',
        paraPwd: 'admin12345',
        paraIp: '200.240.10.206'

      }
    }
  },
  mounted () {
    // 初始化
    this.initWebSocket()

  },
  methods: {
    onConfirm () {
      //需要传输的数据
      let data = {
        code: 1,
        item: '传输的数据'
    }
      this.websocketsend(JSON.stringify(data))
    },

    initWebSocket () { // 初始化weosocket

     this.websock = new WebSocket('ws://localhost:9588/websocket/test');
      //this.websock = new WebSocket('http://localhost:9588/link');

      this.websock.onmessage = this.websocketonmessage
      this.websock.onerror = this.websocketonerror
      this.websock.onopen = this.websocketonopen
      this.websock.onclose = this.websocketclose
    },
    websocketonopen () { // 连接建立之后执行send方法发送数据
      let data = {
        code: 0,
        msg: '这是client:初次连接'
      }
      this.websocketsend(JSON.stringify(data))
    },
    websocketonerror () {
      console.log( 'WebSocket连接失败')
    },
    websocketonmessage (e) { // 数据接收
      console.log('数据接收' + e.data);
      this.receive=e.data;
      console.log(this.receive)
    },
    websocketsend (Data) { // 数据发送
      this.websock.send(Data)
    },
    websocketclose (e) {  // 关闭
      console.log('已关闭连接', e)
    }


  },
  destroyed () {
    // 销毁监听
    this.websock.close();
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
    align-content: center;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

后台代码

package com.dvt.haikangboot.controller;

import com.dvt.haikangboot.common.CommonResult;
import com.dvt.haikangboot.common.ResultUtils;
import com.dvt.haikangboot.pojo.LinkPara;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.*;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/*
 *@author:Nye
 *@discription:writer there
 */
@RestController
@Slf4j
@RequestMapping("/link")
public class LinkParaController {




    @GetMapping("/test")
    public CommonResult test() throws IOException {

        LinkPara linkPara = new LinkPara("admin", "admin12345", "200.240.10.207");
        WebSocketTest.sendInfo(linkPara.toString());
        //webSocketTest.sendMessage("我是后端爸爸");
        //this.sendMessage(linkPara.toString());
        //this.sendMessage("我是后端爸爸");

        return ResultUtils.success(linkPara);
    }

    @PostMapping("/linkPara")
    public CommonResult link(@RequestBody Map<String, String> map){

        if(map.isEmpty()){
            return ResultUtils.error(606,"参数出错");

        }else {
            String paraName = map.get("paraName");
            String paraPwd = map.get("paraPwd");
            String paraIp = map.get("paraIp");
            LinkPara linkPara = new LinkPara(paraName, paraPwd, paraIp);

            return ResultUtils.success(linkPara);
        }
    }
}

maven依赖

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

这里要注意的地方就是 ***private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();***一定要加这个东西,否则后台controller调接口的时候是没办法去调那个sendMessagen那个方法的

package com.dvt.haikangboot.controller;
/*
 *@author:Nye
 *@discription:writer there
 */


import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
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.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@ServerEndpoint("/websocket/test")
@Component
@Slf4j
public class WebSocketTest {

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

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

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        log.info("连接成功");

        try {
            sendMessage("连接成功");

        } catch (IOException e) {
            log.error("网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("onClose连接关闭");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message) throws IOException {
        log.info("log::onMessage方法启用成功"+message);

        this.sendMessage("onMessage方法启用成功"+message);

    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("onError错误原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        log.info("sendInfo报文:"+message);

        for (WebSocketTest item:webSocketSet ) {
            item.sendMessage(message);
        }

    }



}

完美收官

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值