Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native STOMP over websocket

I'm trying to build a React Native messaging app throught websocket and STOMP protocol (For the server side I'm using Spring Boot) but I get a really weird behaviour. My code is the following:

...
import SockJS from 'sockjs-client'; // Note this line
import Stomp from 'stompjs';

function ChatScreen() {
   // Variables declaration

   useEffect(() => {
    const socket = new SockJS('http://localhost:8080/chat');
    const stompClient = Stomp.over(socket);
    const headers = {Authorization: `Bearer ${jwt}`};

    stompClient.connect(headers, () => {
      stompClient.subscribe(
        `/user/${user.username}/queue/messages`, console.log, headers,
      );
    });

    return () => stompClient && stompClient.disconnect();
  }, [jwt, user.username]);

  ...
}

When the above component is mounted I get:

Whoops! Lost connection to http://localhost:8080/chat

Then if I change the SockJS import line from import SockJS from 'sockjs-client'; to import SockJS from 'sockjs-client/dist/sockjs'; without reloading with double "r", but letting hot reloading do its job, I successfully obtain a connection to the websocket and everything works fine. Now, if I reload with double "r" and navigate to ChatScreen component again, I still get the message:

Whoops! Lost connection to http://localhost:8080/chat

Switching back to import SockJS from 'sockjs-client'; from import SockJS from 'sockjs-client/dist/sockjs'; I successfully obtain a new working connection but double "r" breaks it down again.

I tested the code on both an emulator (Android 9) and a physical device (Android 10). I've also tested react-stomp and the result is the same.

For a better understanding on what I mean this is a video that reports the behaviour: https://drive.google.com/open?id=1IVpiJjHsBGkhB38IWoPujI5eXPuBDbf1

I appreciate any help. Thank you

like image 861
Stefano Martella Avatar asked May 23 '20 16:05

Stefano Martella


1 Answers

I found the solution, since I'm on Android emulator I cannot use http://localhost:8080/chat to connect to the websocket, I have to use http://10.0.2.2:8080/chat instead. More details here: https://stackoverflow.com/a/5495789/9121838

like image 69
Stefano Martella Avatar answered Sep 28 '22 20:09

Stefano Martella