注:
1、jdk必须要1.8及以上
2、项目若有接口拦截过滤,WebSocket接口必须要配置拦截,使其可以验证通过
接口:@ServerEndpoint("/webSocket/{username}"),在拦截处配置 /webSocket/*
WebSocket 业务类
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhouhz
* @date
*/
@Slf4j
@Component
@ServerEndpoint("/webSocket/{username}")
public class WebSocketServer {
private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
private Session session;
private String username;
/**
* 连接成功后调用的方法
* @param username
* @param session
* @throws IOException
*/
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
webSocketSet.add(this);
// 在线数加1
int cnt = ONLINE_COUNT.incrementAndGet();
log.info("{}加入连接,当前连接数为:{}", username, cnt);
}
/**
* 连接关闭调用的方法
* @throws IOException
*/
@OnClose
public void onClose() throws IOException {
webSocketSet.remove(this);
int cnt = ONLINE_COUNT.decrementAndGet();
log.info("有连接关闭,当前连接数为:{}", cnt);
}
/**
* 判断是否连接的方法
* @return
*/
public static boolean isServerClose() {
if (webSocketSet.size() == 0) {
log.info("已断开");
return true;
}else {
log.info("已连接");
return false;
}
}
/**
* 收到客户端消息后调用的方法
* @param message
* @throws IOException
*/
@OnMessage
public void onMessage(String message) throws IOException {
log.info("来自客户端的消息:{}", message);
}
/**
* 发生错误时的回调函数
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
/**
* 发送给指定的用户
* @param message
* @param name
* @throws IOException
*/
public void sendMessage(String message, String name) throws IOException {
Session session = null;
for (WebSocketServer item : webSocketSet) {
if (item.username.equals(name)) {
session = item.session;
}
}
if (session == null) {
throw new ServiceException("找不到对应的seesion!");
}
sendInfo(session, message);
}
/**
* 发送给所有用户
* @param message
* @throws IOException
*/
public void sendMessageAll(String message) throws IOException {
for (WebSocketServer item : webSocketSet) {
sendInfo(item.session, message);
}
}
/**
* 发送消息
* @param session
* @param message
* @throws IOException
*/
private void sendInfo(Session session, String message) throws IOException {
session.getAsyncRemote().sendText(message);
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 定时发送
*/
@Scheduled(cron = "0/2 * * * * ?")
private void autoSendInfo() {
log.info("客户端个数:" + webSocketSet.size());
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(item.username + "11111");
} catch (IOException e) {
continue;
}
}
}
}
发送消息的方法文章来源:https://www.toymoban.com/news/detail-508961.html
@Autowired
private WebSocketServer webSocketServer;
public void messagePush(VersionPush versionPush){
//推送消息
MessagePushVo vo = new MessagePushVo();
vo.setVersion(versionPush.getVersion());
vo.setContent(versionPush.getContent());
vo.setCreateDate(DateUtil.format(versionPush.getCreateTime(), "yyyy-MM-dd"));
try {
webSocketServer.sendMessageAll(JSON.toJSONString(vo));
} catch (IOException e) {
e.printStackTrace();
log.error("消息推送失败======>>", e);
}
}
前端代码文章来源地址https://www.toymoban.com/news/detail-508961.html
var limitConnect = 0;
init();
function init() {
var ws = new WebSocket('ws://127.0.0.1:8080/webSocket/zhouhz');
// 获取连接状态
console.log('ws连接状态:' + ws.readyState);
//监听是否连接成功
ws.onopen = function () {
console.log('ws连接状态->onopen:' + ws.readyState);
limitConnect = 0;
//连接成功则发送一个数据
ws.send('我们建立连接啦');
}
// 接听服务器发回的信息并处理展示
ws.onmessage = function (data) {
console.log('接收到来自服务器的消息:');
console.log(data);
//完成通信后关闭WebSocket连接
ws.close();
}
// 监听连接关闭事件
ws.onclose = function () {
// 监听整个过程中websocket的状态
console.log('ws连接状态->onclose:' + ws.readyState);
reconnect();
}
// 监听并处理error事件
ws.onerror = function (error) {
console.log(error);
}
}
function reconnect() {
limitConnect ++;
console.log("重连第" + limitConnect + "次");
setTimeout(function(){
init();
},2000);
}
到了这里,关于JAVA 使用WebSocket发送通知消息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!