服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - Vue+Java 通过websocket实现服务器与客户端双向通信操作

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

2021-10-11 15:20oayoat JavaScript

这篇文章主要介绍了Vue+Java 通过websocket实现服务器与客户端双向通信操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

1. vue代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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实现服务器与客户端双向通信操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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实现服务器与客户端双向通信操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_41754415/article/details/83618266

延伸 · 阅读

精彩推荐