React Native Client Stuck at “Opening Web Socket…”

I’m developing a chat application where the backend is built using Spring Boot, and the frontend is built using React Native with Expo. I’m using STOMP over SockJS to establish a WebSocket connection between the frontend and backend. However, when I attempt to connect, the client gets stuck on “Opening Web Socket…” and never completes the connection.

I’ve configured the WebSocket on the backend, and it seems to be running correctly, but the connection from the frontend fails to proceed beyond the “Opening Web Socket…” stage.

Here is the relevant code:

Frontend: (websocketService.js)

import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';
import { saveMessage } from './messageStorage';
import { encryptMessage, decryptMessage } from './keyManagement';

let stompClient;

export const initializeWebSocket = (userId) => {
    // Replace the brokerURL with a SockJS connection
    const socket = new SockJS('http://192.168.0.34:8080/ws');
    stompClient = new Client({
        webSocketFactory: () => socket,
        connectHeaders: {
            // You can add custom headers here
        },
        debug: (str) => {
            console.log('STOMP: ' + str);
        },
        reconnectDelay: 5000,
        onConnect: (frame) => {
            console.log('Connected to WebSocket:', frame);
            // Subscribe to a topic or queue
            stompClient.subscribe('/queue/messages', (message) => {
                console.log('Received message:', message.body);
                // Decrypt and save message
                const receivedMessage = JSON.parse(message.body);
                handleMessage(receivedMessage);
            });
        },
        onDisconnect: () => {
            console.log('Disconnected from WebSocket');
        },
        onStompError: (frame) => {
            console.error('Broker reported error: ' + frame.headers['message']);
            console.error('Additional details: ' + frame.body);
        },
    });

    stompClient.activate();
};

const handleMessage = async (message) => {
    const privateKey = await getPrivateKey(); // Get the user's private key
    const decryptedMessage = await decryptMessages(message.chatId, privateKey); // Decrypt the message
    await saveMessage(message.chatId, decryptedMessage, message.publicKey); // Save the decrypted message
    console.log('Decrypted and saved message:', decryptedMessage);
};

export const sendMessage = async (chatId, message, publicKey) => {
    if (stompClient && stompClient.connected) {
        const { cipherText, iv } = await encryptMessage(message, publicKey); // Encrypt the message before sending
        const payload = {
            chatId,
            encryptedMessage: cipherText,
            iv,
            publicKey,
            senderId: userId, // Assuming userId is globally accessible or passed in this function
        };
        stompClient.publish({ destination: '/app/chat.sendMessage', body: JSON.stringify(payload) });
    } else {
        console.error('WebSocket is not connected');
    }
};

Backend (WebSocketConfig.java):

package com.Backend.LionsDen.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketConfig.class);

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
        config.setApplicationDestinationPrefixes("/app");
        logger.info("Message broker configured with prefixes /app and destinations /topic, /queue");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();
        logger.info("Registered STOMP endpoints at /ws with SockJS support");
    }
}

I expected the WebSocket connection to be established successfully when the client initiates the connection. However, the connection hangs at “Opening Web Socket…” without progressing. I checked the logs, but there’s no clear indication of why the connection isn’t completing.

What I have tried:

  • Verified the WebSocket URL is correct.
  • Checked that the backend is running and accessible from the device.
  • Ensured that CORS is configured properly on the backend.
  • Added debug logs on both the client and server to diagnose the issue.

New contributor

Fabian Luttenberger is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật