Spring Boot 集成WebSocket 与VUE 实现消息推送

@Configuration

public class WebSocketConfig {

/**

  • 注入ServerEndpointExporter,

  • 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint

*/

@Bean

public ServerEndpointExporter serverEndpointExporter() {

return new ServerEndpointExporter();

}

}

  • 新建实现类:

@Component

@ServerEndpoint(“/ws/awdMatch/{userId}”)

public class AWDMatchWebSocket {

private Session session;

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

private static Map<Long, Session> sessionPool = new HashMap<>();

@OnOpen

public void onOpen(Session session, @PathParam(value = “userId”) Long userId) {

this.session = session;

webSockets.add(this);

sessionPool.put(userId, session);

System.out.println(userId + " 已连接 \n【websocket消息】有新的连接,总数为:" + webSockets.size());

}

@OnClose

public void onClose() {

webSockets.remove(this);

System.out.println(“【websocket消息】连接断开,总数为:” + webSockets.size());

}

@OnMessage

public void onMessage(String message) {

System.out.println(“【websocket消息】收到客户端消息:” + message);

}

/**

  • 此为广播消息

*/

public void sendAllMessage(String message) {

for (AWDMatchWebSocket webSocket : webSockets) {

System.out.println(“【websocket消息】广播消息:” + message);

try {

webSocket.session.getAsyncRemote().sendText(message);

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

  • 此为单点消息

*/

public void sendOneMessage(Long userId, String message) {

System.out.println(“【websocket消息】单点消息:” + message);

Session session = sessionPool.get(userId);

if (session != null) {

try {

session.getAsyncRemote().sendText(message);

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

  • controller 新增调用类:

@Log

@Api(tags = “websocket 测试接口”)

@RestController

@RequestMapping(“ws”)

public class AwdMatchWSTestController {

@Autowired

private AWDMatchWebSocket webSocket;

@GetMapping(“/sendAllWebSocket”)

public String test() {

String text=“你们好!这是websocket群体发送!”;

webSocket.sendAllMessage(text);

return text;

}

@GetMapping(“/sendOneWebSocket/{userId}”)

public String sendOneWebSocket(@PathVariable Long userId) {

String text=userId+" 你好! 这是websocket单人发送!";

webSocket.sendOneMessage(userId,text);

return text;

}

}

  • VUE部分:
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值