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.