2016-06-12 184 views
0

我試圖使用stomp從服務器向客戶端發送消息。我知道在客戶端使用sock.js和stomp我可以從一個用戶發送消息到另一個用戶,而無需多少服務器端交互,只需在控制器方法中使用@SendTo註釋即可。但是,我希望用戶接收的消息是在服務器上生成的(實際上,我發送了一個完整的對象,但爲了簡單起見,我們只是說我試圖發送字符串)。具體而言,這涉及朋友請求接受,並且當一個用戶接受好友請求時,發送請求的人應該收到他的請求被接受的消息。因此,在接受請求的簡單ajax調用rest控制器方法之後,該方法也應該將消息發送給其他用戶。下面的代碼:春天跺腳 - 使用SimpMessagingTemplate從服務器發送消息

@RestController 
@RequestMapping("/rest/user") 
public class UserController{ 
    @Autowired 
    SimpMessagingTemplate simp; 

    @RequestMapping(value="/acceptFriendRequest/{id}", method=RequestMethod.GET, produces = "application/json") 
    public boolean acceptFriendRequest(@PathVariable("id") int id){ 
     UserDTO user = getUser(); // gets logged in user 
     if (user == null) 
      return false; 
     ... // Accept friend request, write in database, etc. 
     String username = ... // gets the username from a service, works fine 
     simp.convertAndSendToUser(username, "/project_sjs/notify/acceptNotification", "Some processed text!"); 
     return true; 
    } 
} 

而這裏的網絡插座配置:

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 

    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
     registry.addEndpoint("/sendNotification").withSockJS(); 

    } 

    @Override 
    public void configureMessageBroker(MessageBrokerRegistry config) { 

     config.enableSimpleBroker("/notify"); 
     config.setApplicationDestinationPrefixes("/project_sjs"); 
    } 


} 

這是JavaScript函數:

function setupWebsockets(){ 
    var socketClient = new SockJS("/project_sjs/sendNotification"); 
    stompClient = Stomp.over(socketClient); 
    stompClient.connect({}, function(frame){ 
     stompClient.subscribe("/project_sjs/notify/acceptNotification", function(retVal){ 
      console.log(retVal); 
     }); 
    }); 
} 

當用戶接受好友請求,一切都寫在數據庫中罰款。當我刷新頁面時,我甚至可以看到其他用戶是我的朋友。但是,其他用戶永遠不會收到他的請求被接受的消息。 有什麼我做錯了嗎?任何幫助將不勝感激。謝謝!

+0

你有答案嗎? –

+0

我用不同的方法解決了這個問題。我沒有訂閱所有用戶到相同的端點「/ project_sjs/notify/acceptNotification」,然後通過用戶名區分它們,我最終將每個用戶訂閱到不同的端點,例如「/ project_sjs/notify/acceptNotification/John123」。這樣,每個用戶名爲John123的人(只有一個人,因爲用戶名是唯一的)會得到通知。它運作得很好。 –

回答

1

我用不同的方法解決了這個問題。我沒有訂閱所有用戶到相同的端點「/ project_sjs/notify/acceptNotification」,然後通過用戶名區分它們,我最終將每個用戶訂閱到不同的端點,例如「/ project_sjs/notify/acceptNotification/John123」。這樣,每個用戶名爲John123的人(只有一個人,因爲用戶名是唯一的)會得到通知。它運作得很好。

+0

你有這個項目的github鏈接嗎?乾杯 –