【发布时间】:2018-04-23 11:44:26
【问题描述】:
好的,我几乎已经阅读了 spring websocket 上的每一篇 stackoveflow 帖子。 我想在特定客户端连接到服务器后向它发送消息,很简单!
我已经能够从客户端进行连接,并且可以在服务器端监听新的连接。但是当我尝试从服务器端发送消息时,什么也没有发生。即使我的客户已经订阅了。
下面是我的客户端js。
var stompClient = null;
$(document).ready(function() {
connect();
});
function connect() {
var socket = new SockJS('/context_path/stockfeeds');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/share', function(message) {
console.log("Subscription successful............");
console.log(JSON.parse(message.body));
});
stompClient.subscribe('/user/queue/reply', function(message) {
console.log("Subscribed to user ...");
});
}, function (error) {
console.log("Stomp protocol error: "+ error);
});
}
$('#livetext').click(function () {
stompClient.send('/app/stockfeeds', {}, 'This is BS');
});
当我单击“#livetext”时,发送发送功能起作用。并在客户端收到响应。 下面是我的控制器。
@Controller
public class StockDispatchController {
@Autowired
LoggerService loggerService;
@MessageMapping("/stockfeeds")
@SendTo("/topic/share")
public String fetchStocks(String message) throws Exception {
loggerService.info("-----------------------------"+ message);
return message;
}
}
下面是我的 Connect 事件监听器
import org.springframework.messaging.simp.SimpMessagingTemplate;
@Component
public class StompConnectEvent implements ApplicationListener<SessionConnectEvent> {
@Autowired
LoggerService logger;
@Autowired
private SimpMessagingTemplate messagingTemplate;
public void onApplicationEvent(SessionConnectEvent event) {
this.messagingTemplate.convertAndSend("/topic/share", "A new client just connected");
this.messagingTemplate.convertAndSendToUser(event.getUser().getName(), "/queue/reply", "I just connected");
logger.info("message template sent");
}
}
当一个新的客户端连接时,事件监听器被触发并运行到最后,但我没有在客户端得到任何响应。
最后,下面是我的应用上下文 xml
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/stockfeeds">
<websocket:handshake-interceptors>
<bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
</websocket:handshake-interceptors>
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic, /queue"/>
</websocket:message-broker>
【问题讨论】: