马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
添加依赖
- <!-- WebSocket 支持 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
复制代码 添加设置类
- @Configuration
- public class WebSocketConfig {
- @Bean
- public ServerEndpointExporter serverEndpointExporter(){
- return new ServerEndpointExporter();
- }
- }
复制代码 添加服务类
- @Component
- @ServerEndpoint("/ws/{clientId}")
- public class WebSocketServer {
- private static Map<String, Session> sessionMap = new HashMap<>();
- @OnOpen
- public void onOpen(Session session, @PathParam("clientId") String clientId) {
- System.err.println("客户端:" + clientId + "建立连结");
- sessionMap.put(clientId, session);
- }
- @OnClose
- public void onClose(@PathParam("clientId") String clientId) {
- sessionMap.remove(clientId);
- }
- /**
- * 收到客户端消息后调用的方法
- *
- * @param message 客户端发送过来的消息
- * @param clientId
- */
- @OnMessage
- public void onMessage(String message, @PathParam("clientId") String clientId) {
- System.err.println("收到来自客户端" + clientId + "的消息:" + message);
- }
- public void sendMessage(String message) {
- Collection<Session> sessions = sessionMap.values();
- for (Session session : sessions) {
- try {
- session.getBasicRemote().sendText(message);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |