简体   繁体   中英

private chat with web socket using spring boot and angular

I am creating a private chat between two people.

on the server side :

@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;
}

on the client side:

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);
  }

How can I tell the websocket which employee I want to send the message on?

I read the documentation regarding STOMP implementation using Spring. Using this technique we push messages to a topic/queue another user has subscribed to but not to another user directly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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