连接关闭后,Spring Boot WebSocket从客户端接收

时间:2019-09-23 19:16:52

标签: java spring-boot websocket spring-websocket duplex

我正在开发spring-boot和Javascript之间的Websocket通信。 我创建了一个简单的后端应用程序和一个简单的网页,该网页使用webSocket启动连接。 服务器端使用Java白色的spring-boot,网页是用Javascript制作的。

spring-boot端发送和接收数据,但是只有在连接关闭后才接收数据! 我想同时进行数据交换

WebSocketConfiguration.java

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Value("${notific.ping}") private String NOTIFIC_PING;
    @Autowired private PingerHandler pingerHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                .addHandler(pingerHandler, NOTIFIC_PING)
                .setAllowedOrigins("*")
        ;
    }

}

PingerHandler.java

@Component
public class PingerHandler extends TextWebSocketHandler {

    @Autowired
    PingNotificServiceEmitter emitterService;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("handleTextMessage");
        System.out.println(message.getPayload());

        session.sendMessage(new TextMessage("Message received"));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        emitterService.addSession( session );
        System.out.println("Ping notific listeningn from "+ session.getId());

    }
}

PingNotificServiceEmitter.java

@Service
public class PingNotificServiceEmitter {

protected List<WebSocketSession> session;

    public void addSession( WebSocketSession newSession ) {
        if( session == null ) session = new LinkedList<WebSocketSession>();
        this.session.add(newSession);
    }

    public void clearSessions() {
        session = null;
    }

    public List<WebSocketSession> getSessions() {
        if( session == null ) session = new LinkedList<WebSocketSession>();
        return session;
    }

    public void emit( String sesId ) {
        try {
            List<WebSocketSession> findSession =
                    session
                            .stream()
                            .filter( ses -> ses.getId().compareTo( sesId ) == 0 )
                            .collect( Collectors.toList() )
                    ;

            if( !findSession.isEmpty() ) {
                System.out.println("emit direct PING notific to "+ findSession.get(0).getId());
                findSession.get(0).sendMessage(new TextMessage("PING"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

0 个答案:

没有答案