Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection keep closing on React Native #632

Open
seungholee-dev opened this issue May 29, 2024 · 1 comment
Open

Connection keep closing on React Native #632

seungholee-dev opened this issue May 29, 2024 · 1 comment

Comments

@seungholee-dev
Copy link

seungholee-dev commented May 29, 2024

Environment

  • Frontend: React Native
  • Backend: Spring with STOMP
  • React Native Version: v13.6.6
  • stompjs Version: v.7.4.0

Issue

  • The logs keep showing me the connection is opened and closed immediately.
  • I saw documentations about React Native issues but had no chance after setting below:
    • text-encoding
    • appendMissingNullonIncoming: true
    • forceBinaryWSFrames: true
    • Also tried downgrading to 5.4.0 where community says it worked but didn't for me
 LOG  Opening Web Socket...
 LOG  Connection closed to ws://localhost:8080/ws
 LOG  STOMP: scheduling reconnection in 5000ms

Code

websocket.js

import { Client } from '@stomp/stompjs';

const socketUrl = 'ws://localhost:8080/ws';

export const connectWebSocket = () => {
    let client = new Client({
        brokerURL: socketUrl,
        debug: (str) => {
            console.log(str);
        },
        appendMissingNULLonIncoming: true,
        forceBinaryWSFrames: true,
        onConnect: () => {
            console.log('Connected');
        },
    });

    client.activate();
}

App.jsx

import * as encoding from 'text-encoding';
import {connectWebSocket} from "./src/config/websocket";

Object.assign(global, encoding)

 useEffect(() => {
     connectWebSocket();
 }, []);

Have I been doing anything wrong?

@Mikail-snipez13
Copy link

I have the same problem but a bit different. I'm thinking this is mainly a problem with the backend with spring boot 3 using websockets. I can connect to the backend when i run the backend on localhost but in deployment the connection fails.

My React Native Code looks like this:

useEffect(() => {
    void getCredentials().then(async credentials => {
      console.log('Configure Websocket')
      const csrfToken = await axios.get(process.env.EXPO_PUBLIC_POST_SERVICE_URL + '/csrf', {
        headers: {
          Authorization: `Bearer ${credentials.accessToken}`
        }
      })
      console.log('Websocket CSRF-TOKEN: ' + csrfToken.data.token)
      wsRef.current = new StompJS.Client({
        // brokerURL: 'ws://localhost:8080/ws',
        // debug: data => { console.log(data) },
        heartbeatIncoming: 10000,
        connectHeaders: {
          'X-Authorization': `Bearer ${credentials.accessToken}`,
          'X-CSRF-TOKEN': csrfToken.data.token
        },
        webSocketFactory: () => {
          return new SockJS(`${process.env.EXPO_PUBLIC_POST_SERVICE_URL}/ws`)  // env = http://localhost:8080
        },
        onConnect: () => {
          console.log('websocket is connected ')
        },
        onStompError: err => {
          console.error('websocket error: %s', err)
        },
        onDisconnect: err => { console.error('websocket error: %s', err) },
        onWebSocketError: err => { console.error('websocket error: %s', err) },
        onUnhandledFrame: err => { console.error('websocket unhandled frame: ' + err)},
        onWebSocketClose: err => { console.error('websocket closed: ' + JSON.stringify(err))}
      })
      wsRef.current.activate()
    }).catch(err => { console.error('noCredentials for websocket: ' + err) })
    return () => {
      if (wsRef.current != null) {
        void wsRef.current.deactivate()
      }
    }
  }, [])

But if i go to the deployment the stompClient throws errors.

websocket closed: {"type":"close","bubbles":false,"cancelable":false,"timeStamp":1717710951199,"wasClean":false,"code":2000,"reason":"All transports failed"}

Screenshot 2024-06-07 at 00 54 22

My Backend configuration is like this:

@Configuration
@EnableWebSocketMessageBroker
@EnableWebSocketSecurity
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
@Slf4j
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {
    
    @Autowired
    private JwtDecoder jwtDecoder;

    @Autowired
    private JwtAuthenticationConverter authenticationConverter;

    private TaskScheduler messageBrokerTaskScheduler;

    @Autowired
    public void setMessageBrokerTaskScheduler(@Lazy TaskScheduler taskScheduler) {
        this.messageBrokerTaskScheduler = taskScheduler;
    }
    
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOrigins("postservice.starlight-marketing.de")
                .addInterceptors(new HttpSessionHandshakeInterceptor())
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic")
                        .setHeartbeatValue(new long[] {10000, 20000})
                        .setTaskScheduler(messageBrokerTaskScheduler);
        registry.setUserDestinationPrefix("/user");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Bean
    AuthorizationManager<Message<?>> messageAuthorizationManager(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
        messages.anyMessage().permitAll();
        return messages.build();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {

        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor =
                        MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    List<String> authorization = accessor.getNativeHeader("X-Authorization");
                    log.info("X-Authorization: {}", authorization.get(0).substring(0, 19));

                    String accessToken = authorization.get(0).split(" ")[1];
                    Jwt jwt = jwtDecoder.decode(accessToken);
                    Authentication authentication = authenticationConverter.convert(jwt);
                    accessor.setUser(authentication);
                }
                return message;
            }
        });
    }
}

I don't know what to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants