Vue+Java 通过websocket实现服务器与客户端双向通信操作

 更新时间:2020年09月22日 10:48:53   作者:oayoat  
这篇文章主要介绍了Vue+Java 通过websocket实现服务器与客户端双向通信操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1. vue代码

methods: {
 //在方法里调用 this.websocketsend()发送数据给服务器
  onConfirm () {
   //需要传输的数据
    let data = {
     code: 1,
     item: ‘传输的数据'
    }
    this.websocketsend(JSON.stringify(data))
  },
  /*
  */
  initWebSocket () { // 初始化weosocket
   let userinfo = getUserInfo()
   let username = userinfo.waiter_userid
   this.websock = new WebSocket('ws://' + baseURL + '/websocket/' + username)

   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)
  },
  websocketsend (Data) { // 数据发送
   this.websock.send(Data)
  },
  websocketclose (e) { // 关闭
   console.log('已关闭连接', e)
  }
 },
 created () {
  console.log('created')
  this.initWebSocket()
 },
 data () {
  return {
   websocket: null
  }
 },
 destroyed () {
  this.websock.close() // 离开路由之后断开websocket连接
 }

2. java代码

项目引入tomcat安装目录里的两个依赖包

package diancan.servlet;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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;

@ServerEndpoint("/websocket/{username}")
public class WebSocket {

  private static int onlineCount = 0;
  private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
  private Session session;
  private String username;

  @OnOpen
  public void onOpen(@PathParam("username") String username, Session session) throws IOException {
  this.username = username;
  this.session = session;

  addOnlineCount();
  clients.put(username, this);
  System.out.println("已连接" + username);
  }

  @OnClose
  public void onClose() throws IOException {
  clients.remove(username);
  subOnlineCount();
  }

  @OnMessage
  public void onMessage(String message) throws IOException {
  DataWrapper res = new DataWrapper();
  System.out.println("message:" + message);
  JSONObject req = JSONObject.parseObject(message);
// System.out.println("item:" + req.getJSONObject("item"));
// System.out.println("item:" + req.getInteger("code"));

  // 发送数据给服务端
  sendMessageAll(JSON.toJSONString(res));
  }

  @OnError
  public void onError(Session session, Throwable error) {
  error.printStackTrace();
  }

  public void sendMessageTo(String message, String To) throws IOException {
  // session.getBasicRemote().sendText(message);
  // session.getAsyncRemote().sendText(message);
  for (WebSocket item : clients.values()) {
   if (item.username.equals(To))
   item.session.getAsyncRemote().sendText(message);
  }
  }

  public void sendMessageAll(String message) throws IOException {
  for (WebSocket item : clients.values()) {
   item.session.getAsyncRemote().sendText(message);
  }
  }

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

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

  public static synchronized void subOnlineCount() {
  WebSocket.onlineCount--;
  }

  public static synchronized Map<String, WebSocket> getClients() {
  return clients;
  }
}

在项目别的类可通过new WebSocket()向客户端发送数据

WebSocket ws = new WebSocket();

ws.sendMessageAll(JSON.toJSONString(rs));

以上这篇Vue+Java 通过websocket实现服务器与客户端双向通信操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 使用vue实现grid-layout功能实例代码

    使用vue实现grid-layout功能实例代码

    这篇文章主要介绍了使用vue实现grid-layout功能的代码讲解,需要的朋友可以参考下
    2018-01-01
  • vueCl如何查看打包后文件的大小占比

    vueCl如何查看打包后文件的大小占比

    这篇文章主要介绍了vueCl如何 查看打包后文件的大小占比问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Nuxt.js SSR与权限验证的实现

    Nuxt.js SSR与权限验证的实现

    这篇文章主要介绍了Nuxt.js SSR与权限验证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • vue使用axios post发送json数据跨域请求403的解决方案

    vue使用axios post发送json数据跨域请求403的解决方案

    这篇文章主要介绍了vue使用axios post发送json数据跨域请求403的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • vue单行文本溢出会出现title提示自定义指令

    vue单行文本溢出会出现title提示自定义指令

    这篇文章主要为大家介绍了vue单行文本溢出会出现title提示自定义指令,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-01-01
  • vue项目本地开发使用Nginx配置代理后端接口问题

    vue项目本地开发使用Nginx配置代理后端接口问题

    这篇文章主要介绍了vue项目本地开发使用Nginx配置代理后端接口问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • Vue中如何引用公共方法和公共组件

    Vue中如何引用公共方法和公共组件

    这篇文章主要介绍了Vue中如何引用公共方法和公共组件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • Vue项目el-upload 上传文件及回显照片和下载文件功能实现

    Vue项目el-upload 上传文件及回显照片和下载文件功能实现

    本次需求是上传多种固定格式的文件,且回显的时候,图片可以正常显示,文件可以进行下载,主要采用element的el-upload组件实现,对Vue项目el-upload 上传文件及回显照片和下载文件功能实现感兴趣的朋友跟随小编一起看看吧
    2023-12-12
  • Vue实现定位并解决内存泄漏

    Vue实现定位并解决内存泄漏

    Vue.js 是一个流行且强大的 JavaScript 框架,它允许我们构建动态和交互式 Web 应用程序,本文我们将深入探讨 Vue.js 应用程序中内存泄漏的原因,并探索如何定位和修复这些问题的有效策略,希望对大家有所帮助
    2023-09-09
  • Vue升级带来的elementui冲突警告:Invalid prop: custom validator check failed for prop “type“.的解决方案

    Vue升级带来的elementui冲突警告:Invalid prop: custom va

    在页面渲染的时候,控制台弹出大量警告,严重影响控制台的信息获取功能,但是页面基本能正常显示,这是因为Vue升级带来的elementui冲突警告: Invalid prop: custom validator check failed for prop “type“.的解决方案,本文给大家介绍了详细的解决方案
    2025-04-04

最新评论