【问题标题】:private chat with web socket using spring boot and angular使用 Spring Boot 和 Angular 与 Web 套接字进行私人聊天
【发布时间】:2021-09-25 01:59:06
【问题描述】:

我正在创建两个人之间的私人聊天。

在服务器端:

@Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue", "/user");
        config.setApplicationDestinationPrefixes("/gkz");
        
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gkz-stomp-endpoint").setAllowedOrigins("http://192.168.100.14:4200").withSockJS();
    }

    @MessageMapping("/hello")
    public void greeting(@RequestBody Message message,Principal principal) throws Exception {

        this.messageRepository.save(message);

        this.messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/greetings", message);
    

    }

@Table(name = "message")
@Entity
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id_message;

    private Date date_message = new Date();

    private String contenu_message;

    @ManyToOne
    @JoinColumn(name = "id_employe")
    private Employe employe;
}

在客户端:

connect() {
    const socket = new SockJS('http://192.168.100.14:8086/gkz-stomp-endpoint');
    this.stompClient = Stomp.over(socket);

    const _this = this;
    this.stompClient.connect({}, function (frame) {

      console.log('Connected: ' + frame);

      _this.stompClient.subscribe('/user/queue/greetings', function (hello) {

        console.log(hello);
          _this.showMessage(JSON.parse(hello.body));
         console.log('Connected: ' + hello.body);
      });
    });


  }

  disconnect() {
    if (this.stompClient != null) {
      this.stompClient.disconnect();
    }
    console.log('Disconnected!');
  }

  showMessage(message) {
    this.messages.push(message);
  }

如何告诉 websocket 我想向哪个员工发送消息?

【问题讨论】:

    标签: javascript java angular spring-boot


    【解决方案1】:

    我阅读了有关使用 Spring 实现 STOMP 的文档。使用这种技术,我们将消息推送到另一个用户订阅的主题/队列,但不会直接发送给另一个用户。

    https://spring.io/guides/gs/messaging-stomp-websocket/

    【讨论】:

    • 请为任何链接添加上下文,以便您的答案是独立的,这意味着答案需要在答案本身中。见"Provide context for links"。如果您可以在此处用自己的话回答问题并仅作为参考链接,那将是更可取的。这是如何运作的?它是如何使用的?显示它如何回答问题.. 虽然问题似乎想知道“我如何告诉 websocket 我想向哪个员工发送消息”。
    猜你喜欢
    • 2017-06-12
    • 2017-09-13
    • 2020-12-22
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多