Websocket : Unexpected response code: 302 - spring-boot

When creating a websocket connection I am getting following exception:
VM74253:149 WebSocket connection to 'wss://HerokuAppName.herokuapp.com/connect2Deploy' failed: Error during WebSocket handshake: Unexpected response code: 302
Spring boot Code for websocket:
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new SocketHandler(), "/connect2Deploy");
}
}
Sockethandler class only has session details because I only want session details to send server details to UI, there wont be any client to server communication.
#Component
public class SocketHandler extends TextWebSocketHandler {
public WebSocketSession sessions = null;
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//the messages will be broadcasted to all users.
sessions = session;
}
public WebSocketSession getSessions() {
return sessions;
}
}
But it always throws error during websocket handshake, am I missing something here?

Related

Is there a way to send websocket message from regular method in spring

I am building web application. There are admin and user roles provided. When user making some action admin is recieving a message that something happened. Websocket connection establishing when user logged. Is there a way to not create ws connection for user and use only HHTP protocol to sending message and send WS message from controller method only?
Now i have theese settings:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS();
}
}
#Controller
public class NotificationController {
#MessageMapping("/notification")
#SendTo("/topic/test")
public Notification getNotification(Notification notification) {
return notification;
}
}
Yes it is possible.
You have to inject SimpleMessagintTemplate, with #Autowire or with constructor.
private final SimpMessagingTemplate simpMessagingTemplate;
public ConstructorName(SimpMessagingTemplate simpMessagingTemplate){
this.simpMessagingTemplate = simpMessagingTemplate;
}
In your controller, or function where you want to send the message to the client use the convertAndSendToUser function.
simpMessagingTemplate.convertAndSendToUser("userId","/private", messageData);
On javascript client side.
var Sock = new SockJS('http://localhost:8080/ws');
stompClient = over(Sock);
stompClient.connect({}, onConnected, onError);
stompClient.subscribe('/topic/' + userId + '/private', onMessageReceived);

There is an endpoint connection error problem implementing the websocket with spring boot

This is my WebSocketConfig.
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/pub");
registry.enableSimpleBroker("/sub");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/socket").setAllowedOriginPatterns("*").withSockJS();
}
}
This is my SocketController:
#Controller
public class SocketController {
#MessageMapping("/comm/message")
#SendTo("/sub/test")
public Message message(Message message) {
return message;
}
}
I am testing the socket through Chrome's Web Socket Test Client and Advanced Rest Client, but my connection endpoint ws://localhost:8080/socket returns the error.
Is there anything I set wrong?
connecting try tool and endPoint
return message

spring websocket send messages to specific users

I am developing a Springboot application which has a websocket server to handle messages coming from different users. I need to develop this server such that a socket client can send messages to specific client. Below given is my WebSocketHandler class.
public class WebSocketHandler extends AbstractWebSocketHandler {
static Logger logger = LogManager.getLogger(WebSocketHandler.class);
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payLoad = message.getPayLoad();
session.sendMessage("message : "+payLoad+" is received!!!");
////
}
}
}
}
I prefer to use a one handler instance as given below.
public class WebSocketConfiguration implements WebSocketConfigurer {
static WebSocketHandler handler = new WebSocketHandler();
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(handler,"/websocket");
}
}
Is there way to achieve this ? Thanks everyone.

How to send message to WebSocket client from Spring WebSocket server using STOMP?

I have two Spring Boot WebSocket applications using STOMP:
WebSocket server
WebSocket client
I am able to send a WebSocket message from the client and respond to it from the server. However, now I would like to send a WebSocket message to the client triggered by an event on the server side.
Can someone tell me a way to do this?
Here is what I have now on the server side:
WebSocketConfig.java:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/alarm");
}
}
WebSocketController.java:
#Controller
public class WebSocketController {
#MessageMapping("/alarm")
#SendTo("/topic/message")
public void processMessageFromClient(#Payload String message, Principal principal) throws Exception {
System.out.println("WEBSOCKET MESSAGE RECEIVED" + message);
}
#RequestMapping(value = "/start/{alarmName}", method = RequestMethod.POST)
public String start(#PathVariable String alarmName) throws Exception {
System.out.println("Starting " + alarmName);
/* SEND MESSAGE TO WEBSOCKET CLIENT HERE */
return "redirect:/";
}
}
I found the answer on the official spring documentation.
You just need to inject a SimpMessagingTemplate.
My controller now looks like this:
#Controller
public class WebSocketController {
private SimpMessagingTemplate template;
#Autowired
public WebSocketController(SimpMessagingTemplate template) {
this.template = template;
}
#MessageMapping("/alarm")
#SendTo("/topic/message")
public void processMessageFromClient(#Payload String message, Principal principal) throws Exception {
System.out.println("WEBSOCKET MESSAGE RECEIVED" + message);
}
#RequestMapping(value = "/start/{alarmName}", method = RequestMethod.POST)
public String start(#PathVariable String alarmName) throws Exception {
System.out.println("Starting " + alarmName);
this.template.convertAndSend("/topic/message", alarmName);
return "redirect:/";
}
}

Large messages failing on Stomp Controller in Spring Boot

I have a stomp controller in a spring boot application, When ever i send a message which exceeds 256kb it fails to enter the controller. I don't see any error messages. Is there any setting where I can configure it to allow larger messages.
Here is my controller
#Component
#Controller
public class DiscussionController {
#MessageMapping("/discussion")
public void post(DiscussionMessage message) {
}
}
Here is my config file
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
private final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("topic");
config.setApplicationDestinationPrefixes("ngdesk");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ngdesk-websocket").setAllowedOrigins("*").withSockJS();
}
}
You need to configure the web-socket transport, e.g.:
#Override
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
registration.setMessageSizeLimit(512 * 1024); // 512K
}

Resources