SpringBoot Websockets gives me a 404 when trying to connect - spring

I'm trying to build a chat using SpringBoot and websockets. When I try to connect to the controller I get a 404 in the debugger. What am I doing wrong?
main.js
function connect(event) {
username = document.querySelector('#name').value.trim();
if (username) {
usernamePage.classList.add('hidden');
chatPage.classList.remove('hidden');
var socket = new SockJS('http://localhost:8080/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, onConnected, onError);
}
event.preventDefault();
}
WebSocketConfig.java
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
}

Related

StompClient Subscribe

Controller
#RestController
#RequestMapping
#CrossOrigin(origins = "*")
public class ProductController {
#Autowired
private ProductService productService;
#SendTo("/topic/all")
public List<Product> findAll() {
return productService.findAll();
}
}
WebSocketConfig
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("http://127.0.0.1:5500").withSockJS();
}
Js Code
function connect() {
let stompClient = null;
let socket = new SockJS('http://localhost:8080/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, (frame) => {
stompClient.subscribe('/topic/all',(response) => {
console.log(JSON.parse(response))
console.log(true)
});
});
}
connect();
hello, this is my small project, my main goal in this project is to show all the products in real time, because when a new product is added by the admin, the same product should be visible to the user. I am using debug stompclient.subscribe not wokring Please help me Thanks

jHipster Websocket return 1006

I am using jHipster to build my backend java app with kwycloak oauth2 authentication, and now, and I want to add websocket support with stomp client.
What I did is add WebsocketConfiguration.java file:
#Configuration
#EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer
{
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/tracker")
.setAllowedOriginPatterns("*")
.withSockJS();
registry.addEndpoint("/stock-ticks").setAllowedOriginPatterns("*").withSockJS();
registry.addEndpoint("/stock-ticks").setAllowedOriginPatterns("*");
}
}
and in frontend js file I would like to call:
function connect() {
let socket = new SockJS('/stock-ticks');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
stompClient.subscribe('/topic/ticks', function (ticks) {
...
});
});
}
However, it always return 1006 error.
I tried the same thing using this Baeldung Example, it works fine without any issue.
Is there any configuration I missed? I am confused

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);

SockJS fails to create/connect to Spring WebSocket

I am learning Spring WebSocket. I have successfully run this Spring WebSocket tutorial. Now I am trying to incorporate it as-is in my existing Spring MVC application. When I run it from Chrome browser, I see below error in its dev console.
Chrome Console
Opening Web Socket...
GET http://localhost:8080/MyAppName/api/gs-guide-websocket/info?t=1497735312528 500 (Internal Server Error) -- abstract-xhr.js:132
Whoops! Lost connection to http://localhost:8080/MyAppName/api/gs-guide-websocket -- stomp.min.js:8
Server Side Error
javax.servlet.ServletException: Could not resolve view with name '/MyAppName/api/gs-guide-websocket/info' in servlet with name 'MyAppName'
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1262)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
Client Side
function connect() {
var socket = new SockJS('/MyAppName/api/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
Server Side
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/MyAppName/api/gs-guide-websocket").withSockJS();
}
}
I have tried to solve this for couple hours now. How do I resolve this?
ty
If your application context is MyAppName then you don't need to specify it in the addEndpoint method - this path is relative to your aaplication context.
Probably registry.addEndpoint("/MyAppName/api/gs-guide-websocket") registers the endpoint with path /MyAppName/MyAppName/api/gs-guide-websocket
Perhaps, mine example will hint the problem
My application base URL
http://localhost:8080/socket/
My js file
function connect() {
var socket = new SockJS('/socket/greeting');
stompClient = Stomp.over(socket);
stompClient.connect({name: 'test'}, function(frame) {
console.log("session Id:" + socket._transport.url);
console.log("user Id:" + socket.current_user_id);
console.log("socket Id:" + stompClient.id);
var sessionId = /\/([^\/]+)\/websocket/.exec(socket._transport.url)[1];
$("#fname").val(sessionId);
console.log("socket Id:" + sessionId);
stompClient.subscribe("/user/queue/errors", function(message) {
alert("Error " + message.body);
});
stompClient.subscribe("/user/queue/reply", function(message) {
showGreeting(message.body);
});
}, function(error) {
alert("STOMP error " + error);
});
}
My socket configuration
package com.connectips.socket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import com.connectips.socket.interceptor.HttpHandshakeInterceptor;
#Configuration
#EnableWebSocketMessageBroker
public class SocketConfig implements WebSocketMessageBrokerConfigurer{
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/", "/queue/");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/greeting").addInterceptors(new HttpHandshakeInterceptor()).withSockJS();
}
}

spring web socket server and react client

i have to develop a web socket server with spring that send to the client a message avery 5 sec. The client is written in react js. This is my server code:
#SpringBootApplication
#EnableAsync
#EnableScheduling
public class TestwsApplication {
public static void main(String[] args) {
SpringApplication.run(TestwsApplication.class, args);
}
}
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chatWS").setAllowedOrigins("*").withSockJS();
}
This is my scheduler that send to the channel /topic/message a message every 5 sec
#Component
public class ScheduledTasks {
#Autowired
WebSocketListener listener;
int i=0;
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
#Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
if (i==0){
listener.pushSystemStatusToWebSocket("ok");
i=1;
}else{
listener.pushSystemStatusToWebSocket("errore");
i=0;
}
}
}
This is my service used by the scheduler to send the message to the clients
#Service
public class WebSocketListener {
#Autowired
private SimpMessagingTemplate webSocket;
#Async
public void pushSystemStatusToWebSocket (String newStatus){
System.out.println("inviooooooooooooooooooooooooooo");
webSocket.convertAndSend("/topic/messages", newStatus);
}
}
This is my react component
import SockJS from 'sockjs-client';
class Main extends React.Component {
constructor() {
super();
this.state = {
clickCount: 0,
};
}
componentDidMount(){
// this is an "echo" websocket service
console.log('didmount')
var sock = new SockJS('http://localhost:8080/chatWS');
sock.onopen = function() {
console.log('open socket ');
sock.send('test');
};
sock.onmessage = function(e) {
console.log('message');
console.log('message', e.data);
sock.close();
};
sock.onclose = function() {
console.log('close');
};
}
on the log i see only the post open socket ... i dont see any log inserted in onmessage... so the client did not receive the message. Why ? Can you help me ?
Thanks
Esoni

Resources