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


Posted in Javascript onSeptember 22, 2020

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安装目录里的两个依赖包

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

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实现服务器与客户端双向通信操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
用 javascript 实现的点击复制代码
Mar 24 Javascript
Jquery 切换不同图片示例代码
Dec 05 Javascript
JavaScript获取表单enctype属性的方法
Apr 02 Javascript
jQuery 移动端artEditor富文本编辑器
Jan 11 Javascript
深入学习AngularJS中数据的双向绑定机制
Mar 04 Javascript
JS获取一个未知DIV高度的方法
Aug 09 Javascript
Javascript 6里的4个新语法
Aug 25 Javascript
javascript中神奇的 Date对象小结
Oct 12 Javascript
在Vuex使用dispatch和commit来调用mutations的区别详解
Sep 18 Javascript
浅析JavaScript异步代码优化
Mar 18 Javascript
详解Jest结合Vue-test-utils使用的初步实践
Jun 27 Javascript
使用JS实现动态时钟
Mar 12 Javascript
Vue实现开关按钮拖拽效果
Sep 22 #Javascript
JS如何生成动态列表
Sep 22 #Javascript
vue使用svg文件补充-svg放大缩小操作(使用d3.js)
Sep 22 #Javascript
解决Can't find variable: SockJS vue项目的问题
Sep 22 #Javascript
解决vue-router 嵌套路由没反应的问题
Sep 22 #Javascript
Js跳出两级循环方法代码实例
Sep 22 #Javascript
vue 二维码长按保存和复制内容操作
Sep 22 #Javascript
You might like
谈谈新手如何学习PHP 默默经典版本
2009/08/04 PHP
php calender(日历)二个版本代码示例(解决2038问题)
2013/12/24 PHP
php中的curl_multi系列函数使用例子
2014/07/29 PHP
php给图片添加文字水印方法汇总
2015/08/27 PHP
PHP使用Pthread实现的多线程操作实例
2015/11/14 PHP
Thinkphp5行为使用方法汇总
2017/12/21 PHP
phpstorm 正则匹配删除空行、注释行(替换注释行为空行)
2018/01/21 PHP
cookie丢失问题(认证失效) Authentication (用户验证信息)也会丢失
2009/06/04 Javascript
jquery设置text的值示例(设置文本框 DIV 表单值)
2014/01/06 Javascript
jQuery实现仿Google首页拖动效果的方法
2015/05/04 Javascript
探究Javascript模板引擎mustache.js使用方法
2016/01/26 Javascript
js实现3D图片展示效果
2017/03/09 Javascript
Angular4表单验证代码详解
2017/09/03 Javascript
nodejs socket服务端和客户端简单通信功能
2017/09/14 NodeJs
vue复合组件实现注册表单功能
2017/11/06 Javascript
手动用webpack搭建第一个ReactApp的示例
2018/04/11 Javascript
Vue.js 踩坑记之双向绑定
2018/05/03 Javascript
vue项目在安卓低版本机显示空白的原因分析(两种)
2018/09/04 Javascript
微信小程序封装的HTTP请求示例【附升级版】
2019/05/11 Javascript
关于vue-cli3打包代码后白屏的解决方案
2020/09/02 Javascript
如何利用 JS 脚本实现网页全自动秒杀抢购功能
2020/10/12 Javascript
在nuxt中使用路由重定向的实例
2020/11/06 Javascript
[02:46]2014DOTA2国际邀请赛 选手为你解读比赛MVP充满梦想
2014/07/09 DOTA
python多线程编程中的join函数使用心得
2014/09/02 Python
python统计字符串中指定字符出现次数的方法
2015/04/04 Python
使用Python导出Excel图表以及导出为图片的方法
2015/11/07 Python
django迁移文件migrations的实现
2020/03/31 Python
基于python实现数组格式参数加密计算
2020/04/21 Python
Html5新增标签有哪些
2017/04/13 HTML / CSS
美国真皮手袋品牌:GiGi New York
2017/03/10 全球购物
Lookfantastic葡萄牙官方网站:欧洲第一大化妆品零售商
2018/03/17 全球购物
俄罗斯厨房产品购物网站:COOK HOUSE
2021/03/15 全球购物
财政局个人总结
2015/03/04 职场文书
python如何在word中存储本地图片
2021/04/07 Python
MySQL中存储时间的最佳实践指南
2021/07/01 MySQL
关于 Python json中load和loads区别
2021/11/07 Python