1. 程式人生 > 程式設計 >Vue+Java 通過websocket實現伺服器與客戶端雙向通訊操作

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安裝目錄裡的兩個依賴包

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實現伺服器與客戶端雙向通訊操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。