繁体   English   中英

使用 spring boot 和 angular 与 web socket 进行私人聊天

[英]private chat with web socket using spring boot and angular

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

在服务器端:

@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 我想向哪个员工发送消息?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM