Search code examples
javajsonspringwebsocketstomp

Spring WebSocket send multiple pair-value message from server


I have been studying the Spring WebSocket example. I would like to create such application that would exchange information from db<->server<->client. I have created my own bean which would make a query to db and in this case it is AnimalBean. Here is the controller of the application:

@Controller
public class GreetingController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message, AnimalBean ab) throws Exception {
        return new Greeting(ab.getCows() + "\t" + new Date() + "\t" + message.getName());
    }

}

Because I want to send different counts of animals like ab.getCows() or ab.getRabbits() etc. to the client I was wondering if it is possible to send it in one JSON message so the example message would look like this:

{"cows":"4", "rabbits":"60"}

Cand it be achieved and what is the simplest way to do that?


Solution

  • Assuming AnimalBean is your DAO Bean. The Updated class would look like.

    @Controller
    public class GreetingController {
    
        @Autowired
        private AnimalBean ab;
    
        @MessageMapping("/hello")
        @SendTo("/topic/greetings")
        public AnimalInfogreeting(HelloMessage message) throws Exception {
            return new AnimalInfo(ab.getCows(), ab.getRabbits());
        }
    
    }
    

    Create POJO class.

    public class AnimalInfo{
       private int cows;
       pirvate int rabbits;
    
       public AnimalInfo(int cows, int rabbits){
           this.cows= cows;
           this.rabbits =rabbits;
       }
    
       //getters and setters
    }