Search code examples
reactjsreact-nativewebsocketstomp

Stomp and SockJs in a React Native


Can anyone provide successful implementation of Stomp + SocketJS inside the React Native project? just how to connect it and use it


Solution

  • These are the most important parts:

    To connect:

    connect = (userId) => {
        if (userId) {
          var socket = new SockJS("http://localhost:1981/ws");
          stompClient = Stomp.over(socket);
    
          stompClient.connect({}, this.onConnected, this.onError);
    
        }
    }
    

    OnConnected you might subscribe or do it in the first step as you wish!:

    onConnected = () => {
        console.log("onConnected");
        // Subscribe to the Public Topic
        stompClient.subscribe("/topic/public", this.onMessageReceived);
    
        // Tell your username to the server
        stompClient.send(
          "/api/chat/addUser/1",
          {},
          JSON.stringify({ sender: "Ali", type: "JOIN" })
        );
    }
    

    onMessageReceived:

    onMessageReceived = (payload) => {
        console.log("onMessageReceived");
        var message = JSON.parse(payload.body);
    }
    

    onError:

    onError = (error) => {
        this.setState({
          error:
            "Could not connect you to the Chat Room Server. Please refresh this page and try again!",
        });
      };
    

    Send message:

    sendMessage = (msg) => {
        var messageContent = "test"
        if (messageContent && stompClient) {
          var chatMessage = {
            sender: this.state.username,
            content: "Heey there",
            type: "CHAT",
          };
          stompClient.send(
            "/api/chat/sendMessage/1",
            {name: "Ali"},
            JSON.stringify(chatMessage)
          );
        }
      };
    

    And you can always go back to the following documentation: [1]: https://stomp-js.github.io/api-docs/latest/classes/Client.html#subscribe