WebSocket SpringBoot使用步骤

一: 加入依赖

    
            org.springframework.boot
            spring-boot-starter-websocket
    

二: 配置 ServerEndpointExporter 暴露Endpoint

@Component
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

三:编写 动作

/**
 * WebSocketEndPoint
 *
 * @author guxiang
 * @date 2017/11/19
 */
@Component
@Slf4j
@ServerEndpoint("/webSocket")
public class WebSocketConnect {

    private Session session;

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


    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose(Session session){
        webSocketSet.remove(this);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
    }

    public void sendMessage(String message) {
        for (WebSocketConnect webSocketConnect: webSocketSet) {
            log.info("【websocket消息】广播消息, message={}", message);
            try {
                webSocketConnect.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

四: 在前端界面编写连接





五:发送消息的实例

image.png

你可能感兴趣的:(WebSocket SpringBoot使用步骤)