Routing websocket destination in Spring-boot - java

Having raw websocket implementation:
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MessageHandler(), "/websocket")
.setAllowedOrigins("*")
.addInterceptors();;
}
}
Handler:
public class MessageHandler extends TextWebSocketHandler {
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// The WebSocket has been closed
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String auth = (String) session.getAttributes().get("auth");
System.out.println(auth);
session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
}
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
// A message has been received
}
}
The websocket client connect to server ( handshake etc. ) with /websocket url e.g ws://localhost:8080/websocket
However, now that connection is estabilished is there a way how to route messages? Lets say i have app that provides chat and some pop-up functionality ( for simplicity lets say the user sends pop-up message and some pop-up window shows to all of his friends in app ).
Ofcourse i would like to route chat messages to /chat and popup to /popup.
One way how to achieve this is to send json message to server and parse it there e.g:
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
String path = getRouteFromJsonMessage(textMessage);
if( ! "".equals(path) && path.equals("chat")
....
if( ! "".equals(path) && path.equals("popup")
....
}
But this seems too slow, parsing json on every message. Is there some other, better way how to achieve routing?
Thanks for help!

Why don't you just register two different MessageHandlers
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatMessageHandler(), "/chat")
.setAllowedOrigins("*")
.addInterceptors()
.addHandler(new PopUpHandler(), "/popup") //etc;
}
}

Related

How to send messages to specific session in Spring through Websockets (STOMP) while multiple connections are open with same user?

I can configure sending messages to specific users with WebSocketMessageBrokerConfigurer and SimpleMessageBroker, it works well.
Problem:
When somebody subscribes on specific userId, I want to send the previous messages from db to that subscriber. But if there already exists a connection and subscription with same userId (e.g. user logs in from another device/browser), old subscriber will receive the initial messages from db too. And with every new subscriber with the same userId, older subscribers will receive the same messages.
So how to send the initial messages from db to specific session, not all sessions?
Is this even possible with STOMP protocol?
Here is the code:
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp/message").setAllowedOrigins("*");
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/chatroom", "/user");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
}
}
public class MessageController {
#MessageMapping("/private-message")
private void receivePrivateMessage(
#Payload Message message,
Principal user,
#Header("simpSessionId") String sessionId) {
log.info("server received private message: " + message);
simpMessagingTemplate.convertAndSendToUser(message.getReceiverId().toString(), "/private-message", message);
}
}
public class EventSubscribeListener implements ApplicationListener<SessionSubscribeEvent> {
private final SimpMessagingTemplate simpMessagingTemplate;
#Override
public void onApplicationEvent(SessionSubscribeEvent event) {
log.info("Stomp subscribed");
TODO get messages from db and send initial messages from db to to specific session/subscriber
}
}
Only idea I had is that I could replace the userId based subscribing to sessionId based subscribing. But that would mean frontend has to get the sessionId and subscribe with it. I don't want FE to deal with that.

How to get Flutter WebSocket working with spring-boot backend?

I have tried many combinations of the values below, I have no idea why it isn't working. I don't even know if the problem is with frontend or backend setup. I pasted the relevant code parts below.
FLutter says the following when I try to connect (MYIPADDRESS is a valid IP address, the IP address of the pc):
WebSocketChannelException: WebSocketChannelException: WebSocketException: Connection to 'http://MYIPADDRESS:8080/topic/greetings#' was not upgraded to websocket
Here is the backend/spring-boot controller part:
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public String send(final String message) throws Exception {
return message;
}
Here is the backend/spring-boot configuration part:
#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("/websocket").withSockJS();
}
}
Here is the frontend/flutter part:
final channel = IOWebSocketChannel.connect(
Uri(
scheme: "ws",
host: "MYIPADDRESS",
port: 8080,
path: "/topic/greetings",
),
);

Spring session + Spring web socket. Send message to specific client based on session id

I have followed Quetion1 and Quetion2 from stack overflow to send messages to specific client, based on its sessionId but could not find success.
Below is my sample RestController class
#RestController
public class SpringSessionTestApi {
#Autowired
public SimpMessageSendingOperations messagingTemplate;
#MessageMapping("/messages")
public void greeting(HelloMessage message, SimpMessageHeaderAccessor headerAccessor) throws Exception {
String sessionId = (String) headerAccessor.getSessionAttributes().get("SPRING.SESSION.ID");
messagingTemplate.convertAndSendToUser(sessionId,"/queue/test",message, createHeaders(sessionId));
}
private MessageHeaders createHeaders(String sessionId) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
headerAccessor.setLeaveMutable(true);
return headerAccessor.getMessageHeaders();
}
}
Session Id: when client sends createSession request, new spring sessionId is generated and same is stored in MongoDB as well. After that when client sends web socket connect request, same sessionId is received which was stored in mongoDb as expected. Till This everything is working fine.
Now my job is to send response back to the client based on the sessionId.
For that I have below web socket class:
#Configuration
#EnableScheduling
#EnableWebSocketMessageBroker
public class WebSocketConfig extends
AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> {
#Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/messages");
}
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue");
registry.setApplicationDestinationPrefixes("/app");
}
}
and the sample client code that I am using to connect is:
function connect() {
stompClient = Stomp.client('ws://localhost:8016/messages');
stompClient.debug = null;
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/queue/test', function (greeting) {
console.log("Hello "+greeting);
console.log("Greeting body "+JSON.parse(greeting.body));
});
});
}
Please help, Where I am doing wrong in this?
Thanks in Advance!
If you are using /user channel as you do, try to pass the user as stated here.
#MessageMapping("/messages")
public void greeting(HelloMessage message, SimpMessageHeaderAccessor headerAccessor, Principal principal)
throws Exception {
messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/test", message);
}
I've found a full workable Spring Stomp Chat project in git, the link is here. You can refer to it.
https://gist.github.com/theotherian/9906304

Extracting Remote endpoint Object from Spring websocket session

In javax websockets we can use something like the follows
Session.getAsyncRemote().sendText(String text)
Session.getBasicRemote().sendText();
How can we send an asynchronous messages using spring websocket.
From WebSocketSession of spring webscockets can we extract RemoteEndPoint and send an async messages
PS Note: I am using Basic Spring websockets...
The configuration and code is as follows:
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
#EnableWebSocket
public class WebMVCConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
private static final String ENDPOINT_URL = "/echo";
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketHandler(), ENDPOINT_URL).setAllowedOrigins("*");
}
#Bean
public WebSocketHandler socketHandler() {
return new WebSocketTestHandler();
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public DefaultHandshakeHandler handshakeHandler() {
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
policy.setInputBufferSize(8192);
policy.setIdleTimeout(600000);
return new DefaultHandshakeHandler(new JettyRequestUpgradeStrategy(new WebSocketServerFactory(policy)));
}
public class SpringMVCInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationConfig.class, RabbitMQConfig.class, RabbitConnectionFactory.class,
WebPropertyPlaceHolderConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
}
#Configuration
public class WebSocketTestHandler extends TextWebSocketHandler {
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
log.info("Connection is established to Server....:: Session Open : {}", session.isOpen());
}
#Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
}
#Override
public void afterConnectionClosed(WebSocketSession curSession, CloseStatus status) throws Exception {
}
}
So inside handleTextMessage(WebSocketSession session,TextMessage message) {
Inside this method am creating multiple threads And sending same session Object and some other parameters..Inside each thread am not modifying any session object related parameters but am trying to execute
TextMessage socketMessage = new TextMessage(message);
session.sendMessage(socketMessage);
}
So each thread is trying to send messages using same session Object..But am facing the following error
java.lang.IllegalStateException: Blocking message pending 10000 for BLOCKING
at org.eclipse.jetty.websocket.common.WebSocketRemoteEndpoint.lockMsg(WebSocketRemoteEndpoint.java:130) ~[websocket-common-9.3.8.v20160314.jar:9.3.8.v20160314]
at org.eclipse.jetty.websocket.common.WebSocketRemoteEndpoint.sendString(WebSocketRemoteEndpoint.java:379) ~[websocket-common-9.3.8.v20160314.jar:9.3.8.v20160314]
at org.springframework.web.socket.adapter.jetty.JettyWebSocketSession.sendTextMessage(JettyWebSocketSession.java:188) ~[spring-websocket-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.web.socket.adapter.AbstractWebSocketSession.sendMessage(AbstractWebSocketSession.java:105) ~[spring-websocket-4.2.4.RELEASE.jar:4.2.4.RELEASE]
So is it possible to send asynchronous messages using spring websockets?
If yes please let me know what configuration changes are required in the above code..Or Can we extract the core AsyncRemoteEndPoint and BasicRemoteEndpoint from spring Websocket Session and can we send asynchronous messages..or if not both the above cases ..move the code to common place and put synchonized(sessionObject)
{
sendmessage
}..Sorry if the framing of question is not clear or already a duplicate question
Please note I am not using any Stomp client or anyother features over spring websocket..Am using plain spring websockets..And is it possible to do without using Future(java feature)(If yes..it would be better)?
I used ConcurrentWebSocketSessionDecorator on the session.
according to:
https://jira.spring.io/browse/SPR-13602
The decorator "enforces sending messages one at a time with a send buffer and send time limit per session. That helps quite a bit to limit the impact of slow clients"

CometD publish a message back to a client

I am having a problem in sending back a message to a client. Below is my code
JavaScript
dojox.cometd.publish('/service/getservice', {
userid : _USERID,
});
dojox.cometd.subscribe('/service/getservice', function(
message) {
alert("abc");
alert(message.data.test);
});
Configuration Servlet
bayeux.createIfAbsent("/service/getservice", new ConfigurableServerChannel.Initializer() {
#Override
public void configureChannel(ConfigurableServerChannel channel) {
channel.setPersistent(true);
GetListener channelListner = new GetListener();
channel.addListener(channelListner);
}
});
GetListener class
public class GetListener implements MessageListener {
public boolean onMessage(ServerSession ss, ServerChannel sc) {
SomeClassFunction fun = new SomeClassFunction;
}
}
SomeClassFunction
class SomeClassFunction(){
}
here i am creating a boolean variable
boolean success;
if it is true send a message to client which is in javascript. how to send a message back to client. i have tried this line also.
remote.deliver(getServerSession(), "/service/getservice",
message, null);
but it is giving me an error on remote object and getServerSession method.
In order to reach your goal, you don't need to implement listeners nor to configure channels. You may need to add some configuration at a later stage, for example in order to add authorizers.
This is the code for the ConfigurationServlet, taken from this link:
public class ConfigurationServlet extends GenericServlet
{
public void init() throws ServletException
{
// Grab the Bayeux object
BayeuxServer bayeux = (BayeuxServer)getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
new EchoService(bayeux);
// Create other services here
// This is also the place where you can configure the Bayeux object
// by adding extensions or specifying a SecurityPolicy
}
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
throw new ServletException();
}
}
This is the code for EchoService class, taken fro this link:
public class EchoService extends AbstractService
{
public EchoService(BayeuxServer bayeuxServer)
{
super(bayeuxServer, "echo");
addService("/echo", "processEcho");
}
public void processEcho(ServerSession remote, Map<String, Object> data)
{
// if you want to echo the message to the client that sent the message
remote.deliver(getServerSession(), "/echo", data, null);
// if you want to send the message to all the subscribers of the "/myChannel" channel
getBayeux().createIfAbsent("/myChannel");
getBayeux().getChannel("/myChannel").publish(getServerSession(), data, null);
}
}

Categories

Resources