欢迎来到代码驿站!

vue

当前位置:首页 > 网页前端 > vue

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

时间:2021-04-15 11:19:34|栏目:vue|点击:

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路由导航守卫和请求拦截以及基于node的token认证的方法

栏    目:vue

下一篇:解决vue.js this.$router.push无效的问题

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

本文地址:http://www.codeinn.net/misctech/101939.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有