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

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。