springboot+stomp 点对点通信一直不通?
想用stomp实现服务端和客户端一对一通信,类似聊天性质的功能,但是一直调不通,上代码:
这是配置类
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//允许跨域允
// 许客户端采用socket
//路径"/stomp"被注册为STOMP端点,对外暴露,客户端通过该路径接入WebSocket服务
registry.addEndpoint("/stomp").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//订阅的前缀
registry.enableSimpleBroker("/queue", "/topic");
//全局使用的订阅前缀(相当于工程名)客户端send时前缀;@MessageMapping时用到 "app/@MessageMapping("msg")"
registry.setApplicationDestinationPrefixes("/app");
//点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
registry.setUserDestinationPrefix("/user");
}
这是客户端的链接
var stomp =null;
var url = "localhost:8080/stomp"
function messageConnect(){
var sock = new SockJS(url);
stomp = Stomp.over(sock);
let myName = $("#myName").val()
stomp.connect({},function (frame) {
stomp.subscribe("/user/"+myName+"/test",reciveMessage);
// stomp.subscribe("/topic/msg",reciveMessage);
})
}
function reciveMessage(msg){
console.log(msg);
let value = JSON.stringify(msg)
alert(value)
}
这是服务端给客户端发送消息的2种方式:
/**
* 接收客户端发送的消息
* 访问路径为:setApplicationDestinationPrefixes(配置类里面设置的mywebsocket)+msg
* @return
*/
@MessageMapping("msgto/{userName}")
@SendToUser("/queue/msg")
public void forwardMsg(@RequestBody TestMsg msg, @DestinationVariable String userName){
System.err.println("server收到消息"+msg.toString());
TestMsg msg2 = new TestMsg(1, "这是server发出的消息");
simpMessagingTemplate.convertAndSendToUser(userName,"/test",msg2);
}
// @MessageMapping("msg2All")
// public void msg2All(@RequestBody TestMsg msg){
// System.err.println("server收到消息"+msg.toString());
// TestMsg msg2 = new TestMsg(1, "这是群发出的消息");
// simpMessagingTemplate.convertAndSend("/topic/msg",msg2);
// }
@GetMapping("bb")
public void forwardMsg2(){
simpMessagingTemplate.convertAndSendToUser("zc1","/test",new TestMsg(1,"这是server发出的消息2"));
return ;
}
}
现在是不管
let send = stomp.send("/app/msg2All", {}, JSON.stringify({ "code": 1, //消息内容 "msg": "大家好" //接收人 }));
还是localhost:8080/bb
浏览器端都收不到消息
ps:广播消息的模式已经测试通过了。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
stomp.subscribe("/user/"+myName+"/queue/test",reciveMessage); 这样的订阅 应该怎么发消息呢
订阅是这个地址,而你发送的时候是
这么订阅也不行(统一加个)
上面调用代码多了个
为什么不通呢???????????????