2016-08-04 72 views
0

我坚持用弹簧4上的WebSockets以下问题,不知道为什么这样的代码:Spring和WebSocket的

@MessageMapping("/hello") 
@SendTo("/topic/greetings") 
public Greeting greeting(HelloMessage message) throws Exception { 
    Thread.sleep(3000); 
    return new Greeting("Hello, " + message.getName() + "!"); 
} 

工作正常,为什么这个剂量不:

@MessageMapping("/hello") 
public void hehe(HelloMessage message){ 
    try { 
     greeting(message); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
@SendTo("/topic/greetings") 
public Greeting greeting(HelloMessage message) throws Exception { 
    Thread.sleep(3000); 
    return new Greeting("Hello, " + message.getName() + "!"); 
} 

进出口寻找解决方案如果服务器端事件发生,如何调用greeting()方法,

感谢您的帮助。

回答

0

将它们分开将不起作用!

@MessageMapping("/hello") 
@SendTo("/topic/greetings") 
public Greeting greeting(HelloMessage message) throws Exception { 
    Thread.sleep(3000); 
    return new Greeting("Hello, " + message.getName() + "!"); 
} 

。如果您要发送到目的地的服务器端事件,你应该使用:

simpMessagingTemplate.convertAndSend("/user/" + username + "/topic/greetings", 
     new Greeting("Hello, " + message.getName() + "!")); 
// username should refer to the user in socket header if you want to send to a specific user 
// omit the prefix /user/<username> if you are broadcasting 

其中SIMP使用(你可以使用通讯uitlities像rabbitMQ太):

@Autowired 
org.springframework.messaging.simp.SimpMessagingTemplate simpMessagingTemplate;