Java + Vue WebSocket 通讯
后端 Socket代码=================
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Semaphore;
/**
* 信号量相关处理
*
*/
@Slf4j
public class SemaphoreUtils {
/**
* 获取信号量
*
*/
public static boolean tryAcquire(Semaphore semaphore) {
boolean flag = false;
try {
flag = semaphore.tryAcquire();
} catch (Exception e) {
log.error("获取信号量异常", e);
}
return flag;
}
/**
* 释放信号量
*/
public static void release(Semaphore semaphore) {
try {
semaphore.release();
} catch (Exception e) {
log.error("释放信号量异常", e);
}
}
}
//===================WebSocketConfig 配置==========================
package com.smartby.common.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* websocket 配置
*
* @author smartby
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
//===================WebSocketServer 4个主要方法OnOpen、 OnClose、 @OnError、@OnMessage=====================
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;
/**
* websocket 消息处理
*
* @author smartby
*/
@Component
@ServerEndpoint("/websocket/message/{userId}")
@Slf4j
public class WebSocketServer {
/**
* 默认最多允许同时在线人数100
*/
public static int socketMaxOnlineCount = 100;
private static final Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(@PathParam("userId") String userId,Session session) throws Exception {
boolean semaphoreFlag = false;
// 尝试获取信号量
semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
if (!semaphoreFlag) {
// 未获取到信号量
log.error("\n 当前在线人数超过限制数======== {}", socketMaxOnlineCount);
WebSocketUtils.sendMessageToUserByText(session, "当前在线人数超过限制数:" + socketMaxOnlineCount);
session.close();
} else {
// 添加用户
WebSocketUtils.put(userId, session);
log.info("\n 建立连接 ======= {}", userId);
log.info("\n 当前人数 ======= {}", WebSocketUtils.getUsers().size());
WebSocketUtils.sendMessageToUserByText(session, "连接成功");
}
}
/**
* 连接关闭时处理
*/
@OnClose
public void onClose(@PathParam("userId") String userId,Session session) {
log.info("\n 关闭连接 ======= {}", userId);
// 移除用户
WebSocketUtils.remove(userId);
// 获取到信号量则需释放
SemaphoreUtils.release(socketSemaphore);
}
/**
* 抛出异常时处理
*/
@OnError
public void onError(@PathParam("userId") String userId,Session session, Throwable exception) throws Exception {
if (session.isOpen()) {
// 关闭连接
session.close();
}
log.info("\n 连接异常 ======= {}", userId);
log.info("\n 异常信息 ======= {}", exception);
// 移出用户
WebSocketUtils.remove(userId);
// 获取到信号量则需释放
SemaphoreUtils.release(socketSemaphore);
}
/**
* 服务器接收到客户端消息时调用的方法
*/
@OnMessage
public void onMessage(@PathParam("userId") String userId,String message, Session session) {
String msg = message+ "你好!!!!";
WebSocketUtils.sendMessageToUserByText(session, msg);
}
}
//==========================操作客户端用户方法==================================
import lombok.extern.slf4j.Slf4j;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* websocket 客户端用户集
*
* @author smartby
*/
@Slf4j
public class WebSocketUtils {
/**
* 用户集
*/
private static final Map<String, Session> USERS = new ConcurrentHashMap<>();
/**
* 存储用户
*
* @param key 唯一键
* @param session 用户信息
*/
public static void put(String key, Session session) {
USERS.put(key, session);
}
/**
* 移除用户
*
* @param session 用户信息
* @return 移除结果
*/
public static boolean remove(Session session) {
String key = null;
boolean flag = USERS.containsValue(session);
if (flag) {
Set<Map.Entry<String, Session>> entries = USERS.entrySet();
for (Map.Entry<String, Session> entry : entries) {
Session value = entry.getValue();
if (value.equals(session)) {
key = entry.getKey();
break;
}
}
} else {
return true;
}
return remove(key);
}
/**
* 移出用户
*
* @param key 键
*/
public static boolean remove(String key) {
log.info("\n 正在移出用户 ========= {}", key);
Session remove = USERS.remove(key);
if (remove != null) {
boolean containsValue = USERS.containsValue(remove);
log.info("\n 移出结果 ========== {}", containsValue ? "失败" : "成功");
return containsValue;
} else {
return true;
}
}
/**
* 获取在线用户列表
*
* @return 返回用户集合
*/
public static Map<String, Session> getUsers() {
return USERS;
}
/**
* 群发消息文本消息
*
* @param message 消息内容
*/
public static void sendMessageToUsersByText(String message) {
Collection<Session> values = USERS.values();
for (Session value : values) {
sendMessageToUserByText(value, message);
}
}
/**
* 发送文本消息
*
* @param session 自己的用户名
* @param message 消息内容
*/
public static void sendMessageToUserByText(Session session, String message) {
if (session != null) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("\n[发送消息异常]", e);
}
} else {
log.info("\n[已离线]");
}
}
}
**前端Vue代码============================**
created() {
this.initWebSocket()
},
destroyed () {
this.websock.close() // 离开路由之后断开websocket连接
},
methods: {
//在方法里调用 this.websocketsend()发送数据给服务器
onConfirm () {
//需要传输的数据
let data = {
code: 1,
item: ''
}
this.websocketsend(JSON.stringify(data))
},
/*
*/
initWebSocket () { // 初始化weosocket
// let userinfo = {userId:'111804SXK01'}
this.websock = new WebSocket('ws://' + ip:port' + '/websocket/message/'+userId)
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)
if(e.data === 'refresh'){
this.handlequery()
}
},
websocketsend (Data) { // 数据发送
this.websock.send(Data)
},
websocketclose (e) { // 关闭
console.log('已关闭连接', e)
},
}
使用示例,具体操作可根据自己需要修改