Tal Shani
Tal Shani

Reputation: 690

WebSocket between react native and java

I have an app in react native and my server is in java (java spring).

Im trying to have real time data with webSocket but can connect between them. I was working with react-native-websocket for react native and with messaging-stomp-websocket for the server in java spring.

I couldn't be able to connect between them.

code from react native:

<WS ref={ref=> {this.ws = ref}}
    url="ws://echo.websocket.org/"
    onOpen={() => {
    console.log('Open!')
    //this.ws.send('Hello')
    }}
    onMessage={(msg)=>{console.log('Message!',msg)}}
    onError={(err)=>{console.log('Error websocket!',err)}}
    onClose={(close)=>{console.log('Close!',close)}}
    reconnect // Will try to reconnect onClose
/>

code from the server:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //the client subscribe (listen) to /dispenser
        config.enableSimpleBroker("/dispenser");
        //perfix for the client. it should be on the client /app/{MessageMapping variable}
        config.setApplicationDestinationPrefixes("/app");
    }

}

If this is not the way to do real time data I would like to know if there's different way

Upvotes: 4

Views: 1326

Answers (1)

Udith Shalinda
Udith Shalinda

Reputation: 487

You can use sockjs-client and stompjs.

importing them

import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

You have to execute below lines and to subscribe that path.

    //your end point here
    var sock = new SockJS('http://localhost:8102/api/ws');
let stompClient = Stomp.over(sock);
sock.onopen = function() {
  console.log('open');
}
stompClient.connect({}, function (frame) {
   console.log('Connected: ' + frame);
   //subscribing path
   stompClient.subscribe('/topic/public', function (greeting) {
     console.log(greeting);
     //you can execute any function here
   });
});

When you want to send the message

stompClient.send("/app/sendMessage", {},"your message here");

Upvotes: 2

Related Questions