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)
ssage = this.websocketonmessage
r = this.websocketonerror
pen = this.websocketonopen
lose = 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 urrent.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;
websocket和socket
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 {
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:" + JSONObject("item"));
// System.out.println("item:" + Integer("code"));
// 发送数据给服务端
JSONString(res));
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// BasicRemote().sendText(message);
// AsyncRemote().sendText(message);
for (WebSocket item : clients.values()) {
if (item.username.equals(To))
AsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
AsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
}
public static synchronized void subOnlineCount() {
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}
在项⽬别的类可通过new WebSocket()向客户端发送数据
WebSocket ws = new WebSocket();
ws.JSONString(rs));
以上这篇Vue+Java 通过websocket实现服务器与客户端双向通信操作就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。