需要引入的依赖:

org.springframework.boot

spring-boot-starter-websocket

org.java-websocket

Java-WebSocket

1.3.5

2.创建config

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.socket.config.annotation.EnableWebSocket;

import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**

* 配置ServerEndpointExporter, 将Endpoint暴露出去让客户端来建立连接.

*/

@Configuration

@EnableWebSocket

public class WebsocketConfig {

@Bean

public ServerEndpointExporter serverEndpoint() {

return new ServerEndpointExporter();

}

}

3.创建自己的websocket公共类

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import org.springframework.util.StringUtils;

import javax.websocket.OnClose;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import java.util.concurrent.CopyOnWriteArraySet;

//用于前端和websocket连接的地址信息

@ServerEndpoint("/myWs")

@Component

@Slf4j

public class WsServerEndpoint {

private Session session;

/**

* 缓存 webSocket连接到单机服务class中(整体方案支持集群),WsServerEndpoint是当前的类名称

*/

private static final CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet<>();

/**

* 第一次连接websocket执行的方法

*

* @param session

*/

@OnOpen

public void onOpen(Session session) {

try {

this.session = session;

webSockets.add(this);

log.info("【websocket消息】有新的连接,总数为:" + webSockets.size());

session.getBasicRemote().sendText("【websocket消息】有新的连接,总数为:" + webSockets.size());

} catch (Exception e) {

log.error("websocket打开异常", e);

}

}

/**

* 关闭websocket执行的方法

*/

@OnClose

public void onClose(){

try {

webSockets.remove(this);

log.info("【websocket消息】连接断开,总数为:" + webSockets.size());

} catch (Exception e) {

log.error("websocket关闭异常", e);

}

}

/**

* 接收到消息 用于前端调用时候回传的数据

* @param message 参数,自定义其它类型入参

*/

@OnMessage

public void onMsg(String message){

try

{ this.session.getBasicRemote().sendText(message); } catch (IOException e) { log.error("发送给消息异常", e); }

}

//自定义方法,用于主动传递给前端的方法,用于在代码中其它类方法里面调用

public void pushMessage(String message) {

webSockets.forEach(ws -> {

Session sess = ws.session;

synchronized (sess) { // 1. 不能多线程操作同一个session

try {

if (sess.isOpen()) {

// 2.必须是同步发送

ws.session.getBasicRemote().sendText(message); // 3.不满足以上两种情况时会抛出异常:The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method

} else {

sess.close();

webSockets.remove(ws);

log.error("session状态:{},手动关闭", sess.isOpen());

}

} catch (Exception e) {

log.error("发送消息:{},失败", message, e);

try {

sess.close();

webSockets.remove(ws);

} catch (IOException ioException) {

log.error("关闭session失败", ioException);

}

}

}

});

}

}

4.验证websocket是否正常的测试工具地址:在线websocket测试-在线工具-postjson

参考文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。