Spring 4 websocket without STOMP,socketjs
Asked Answered
M

3

18

I am trying to test websocket without using socketjs library and also i don't want to add any stomp connection.

I am following the example from stackoverflow question: WebSocket with Sockjs & Spring 4 but without Stomp

So without stomp server , I have succeeded to connect via socketjs library with a url : ws://localhost:8080/greeting/741/0tb5jpyi/websocket

And now I want to remove the socketjs library to allow raw websocket connection(may be devices such as android,ios, etc...)

When I remove the parameter : .withSockJS(), I couldn't connect via websocket.

I tried the following URLs, but they didn't work:

ws://localhost:8080/greeting/394/0d7xi9e1/websocket not worked
ws://localhost:8080/greeting/websocket not worked
ws://localhost:8080/greeting/ not worked 

which URL should i use to connect ?

Mcadoo answered 28/8, 2015 at 8:51 Comment(1)
how did you manage the upgrade request to tomcat indicating that "update the protocol form http to ws"Otten
D
8

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

new WebSocket('ws://localhost:8080/greeting')
Dielle answered 28/8, 2015 at 10:31 Comment(4)
its worked with javascript but with advanced rest client , I have received 403 forbidden error.Mcadoo
The default behaviour is to accept only same origin requests, this might give you a 403 when using the Advanced Rest Client. Configure the allowed origins on your endpoint: registry.addHandler(greetingHandler(), "/greeting").setAllowedOrigins("*");Dielle
How to configure WebSocketConfigurer with security, I mean with something like new WebSocket('wss://localhost:8080/greeting'). I do not want to use stomp/sockjs as the client is third party where I do not have control and only option is plain TextWebSocketHandler for meDisaffiliate
@Chakri In order to configure the websocket with security you should simply activate the ssl mode in spring vial the property server.ssl.enabled=true the full configuration can be found in the link: baeldung.com/spring-boot-https-self-signed-certificateEnwomb
B
18

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
@EnableWebSocket
public 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.

@Component
public 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());
        ...
    }
}
Brynnbrynna answered 28/8, 2015 at 9:13 Comment(8)
thanks for your reply duffy356, I have the same configuration. I am trying to test my connection over chrome advanced rest client plugin. On my previous project I was able to connect websocket over that plugin. But the project was not spring based.Now I can not connect websocket via url : ws://localhost:8080/greeting/ . I couldnt find the right url to connect . have any idea?Mcadoo
does the chrome advanced rest client plugin support websockets?Brynnbrynna
try to connect to your Server frome chrome console.Brynnbrynna
@Brynnbrynna thanks for your answer. Is it possible to make websockets without STOMP work via ssl (wss)?Chalice
What tool I can use to test it? I used WebSocket Client and sockettest.sourceforge.net and nothing happen Only I got : Error parsing HTTP request header java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokensLargess
@user3871754 These are Websockets, the tool you used is for TCP/UDP Sockets. The implementation of my answer is for Spring-boot with Tomcat as the WebServer.Brynnbrynna
What tool I can use to test it?Largess
@Chalice In order to configure the websocket with security you should simply activate the ssl mode in spring vial the property server.ssl.enabled=true the full configuration can be found in the link: baeldung.com/spring-boot-https-self-signed-certificateEnwomb
D
8

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

new WebSocket('ws://localhost:8080/greeting')
Dielle answered 28/8, 2015 at 10:31 Comment(4)
its worked with javascript but with advanced rest client , I have received 403 forbidden error.Mcadoo
The default behaviour is to accept only same origin requests, this might give you a 403 when using the Advanced Rest Client. Configure the allowed origins on your endpoint: registry.addHandler(greetingHandler(), "/greeting").setAllowedOrigins("*");Dielle
How to configure WebSocketConfigurer with security, I mean with something like new WebSocket('wss://localhost:8080/greeting'). I do not want to use stomp/sockjs as the client is third party where I do not have control and only option is plain TextWebSocketHandler for meDisaffiliate
@Chakri In order to configure the websocket with security you should simply activate the ssl mode in spring vial the property server.ssl.enabled=true the full configuration can be found in the link: baeldung.com/spring-boot-https-self-signed-certificateEnwomb
M
3

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("*");
Methylene answered 8/7, 2021 at 6:44 Comment(1)
After hours of trial and error, this did it for me. Thank you!Wiper

© 2022 - 2024 — McMap. All rights reserved.