Websocket使用——Spring Boot配置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();
    }

}
  • 創建service
@Component
@ServerEndpoint("/websocket/{userName}")
public class WebSocketServiceImpl {
    private Session session;

    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userName")String userName) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(userName, session);
        System.out.println(userName+"【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(WebSocketServiceImpl webSocket : webSockets) {
            System.out.println("【websocket消息】廣播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此為單點消息
    public void sendOneMessage(String userName, String message) {
        System.out.println("【websocket消息】單點消息:"+message);
        Session session = sessionPool.get(userName);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
    • 注意此處@ServerEndpoint注解的值要和前端通信的接口地址保持一致,否則不能連接通信。
  • Websocket Server 已經搭建完成,客戶端已經可以和服務端通信了。服務端 向客戶端推送消息 通過 session.getBasicRemote().sendText(message)

測試

  • 代碼如下
@RequestMapping("/websocket")
@RestController
public class WebSocketController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WebSocketServiceImpl webSocketService;

    @ResponseBody
    @GetMapping("/sendAllWebSocket")
    public String test() {
        String text="你們好!這是websocket群體發送!";
        webSocketService.sendAllMessage(text);
        return text;
    }

    @GetMapping("/sendOneWebSocket/{userName}")
    public String sendOneWebSocket(@PathVariable("userName") String userName) {
        String text=userName+" 你好! 這是websocket單人發送!";
        webSocketService.sendOneMessage(userName,text);
        return text;
    }
}
    • 通過url測試通信結果,前端可以打印信息


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM