Spring 4 websocket without STOMP,socketjs Spring 4 websocket without STOMP,socketjs spring spring

Spring 4 websocket without STOMP,socketjs


I'm using websockets without STOMP in my project.

The following configuration works with spring-boot.

add spring boot websocket dependency in pom.xml

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-websocket</artifactId>    <version>${spring-boot.version}</version></dependency>

Then add a class (here WebSocketServerConfiguration.java), which configures your websocket:

@Configuration@EnableWebSocketpublic class WebSocketServerConfiguration implements WebSocketConfigurer {    @Autowired    protected MyWebSocketHandler webSocketHandler;    @Override    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {        registry.addHandler(webSocketHandler, "/as");    }}

finally you can write your WebsocketHandler. Spring provides you different abstract classes for WebSocketHandlers (in main-package: org.springframework.web.socket.handler). My websocket is configured without STOMP and my client doesn't use socket.js. Therefore MyWebSocketHandler extends TextWebSocketHandler and overrides the methods for errors, opening and closing connections and received texts.

@Componentpublic class MyWebSocketHandler extends TextWebSocketHandler {    ...    @Override    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {        LOG.error("error occured at sender " + session, throwable);        ...    }    @Override    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {        LOG.info(String.format("Session %s closed because of %s", session.getId(), status.getReason()));        ...    }    @Override    public void afterConnectionEstablished(WebSocketSession session) throws Exception {        LOG.info("Connected ... " + session.getId());        ...    }    @Override    protected void handleTextMessage(WebSocketSession session, TextMessage jsonTextMessage) throws Exception {        LOG.debug("message received: " + jsonTextMessage.getPayload());        ...    }}


You should use ws://localhost:8080/greeting:

new WebSocket('ws://localhost:8080/greeting')


I also face the same situation on client side client canot connect to the server.

What works me is add bellow setAllowedOrigins("*") to the Custom Handler.

registry.addHandler(webSocketHandler, "/app").setAllowedOrigins("*");