好的,我已经阅读了关于Spring WebSocket的几乎所有stackoverflow帖子。
我想在特定客户端连接到服务器后发送一条消息,很简单!
我已经能够从客户端连接,并且可以在服务器端侦听新连接。但是当我尝试从服务器端发送消息时,什么也没有发生。即使我的客户端已经订阅了。
以下是我的客户端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>