Not able to connect using Sockjs-client and stompjs in ReactNative 0.76.6
Hi, I have followed https://stomp-js.github.io/faqs/2019/05/20/faqs.html before reporting and followed fixes from the closed issue , but nothing works,
am using RN 0.76.6
Below is my dependencies :
"dependencies": {
"react": "18.3.1",
"react-native": "0.76.6",
"@stomp/stompjs": "^7.0.0",
"sockjs-client": "^1.6.1",
"text-encoding": "^0.7.0"
},
"devDependencies": {
"@types/sockjs-client": "^1.5.4",
"@types/text-encoding": "^0.0.40",
}
Am trying to connect to a end point with https://<URL>, but nothing works, am not able to connect to the springboot end points
Below is my Code to connect
- I installed and then textencoder in my index.js, also tried with app.tsx
import * as encoding from 'text-encoding';
global.TextEncoder = encoding;
- in my app.tsx
import { Client, Stomp } from '@stomp/stompjs';
import SockJS from 'sockjs-client';
function App(): React.JSX.Element {
const [stompClient, setStompClient]: any = useState(null);
const [isSocketConnected, setIsSocketConnected] = useState(false);
useEffect(() => {
initSocket()
return () => {
if (stompClient) {
stompClient.deactivate(); // Clean up the connection on component unmount
}
};
}, []);
const initSocket = async () => {
try {
const endpoint = "https://endpoint_url:443"
// const socket = new SockJS(`${endpoint}`, null, {
// // transports: ['websocket', 'xhr-streaming', 'xhr-polling'],
// // server: "https://endpoint_url",
// });
const socket = new SockJS(`${endpoint}`);
console.log({ socket }, Stomp);
const sClient = new Client({
webSocketFactory: () => socket, // Use SockJS
reconnectDelay: 5000, // Reconnect after 5 seconds
heartbeatIncoming: 4000, // Heartbeat for incoming messages
heartbeatOutgoing: 4000, // Heartbeat for outgoing messages
forceBinaryWSFrames: true,
appendMissingNULLonIncoming: true,
logRawCommunication: true,
connectHeaders: {},
onChangeState: (state: any) => {
console.log("%c onChangeState", "background: #ff000045;", state);
}
});
sClient.debug = async (resp: any) => {
console.log('STOMP Debug:', resp);
};
console.log("sClient", sClient)
sClient.onConnect = async (frame: any) => {
console.log('%c STOMP connected', 'background: #4caf50; color: white;', frame);
setIsSocketConnected(true);
};
sClient.onDisconnect = (frame: any) => {
console.log('%c STOMP disconnected', 'background: red; color: white;', frame);
setIsSocketConnected(false);
retryConnection();
};
sClient.onStompError = (frame: any) => {
console.error('STOMP Error:', frame);
setIsSocketConnected(false);
};
// Activate the connection
sClient.activate();
setStompClient(sClient);
} catch (error) {
console.error('Error initializing socket:', error);
}
};
also added clearText in manifest, but nothing either http or https both not connecting but the endpoint_url is working fine with other technologies.
Please help me with this anyone !.
I am also facing the same issue with react native and spring boot. Can someone help me in this issue ? Below is the sample Test code for react native:
import { Client, Versions } from "@stomp/stompjs"; import { useState, useEffect } from "react"; import { Button, Text, View } from "react-native"; import SockJS from "sockjs-client";
export const Test = () => {
const [stompClient, setStompClient] = useState<Client | null>(null);
useEffect(() => {
const socket = new SockJS('http://192.168.1.6:8080/ws-location');
const client = new Client({
webSocketFactory: () => socket,
debug: str => console.log(str),
stompVersions: new Versions([Versions.V1_2]),
forceBinaryWSFrames: true,
logRawCommunication: true,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
onWebSocketClose: () => {
console.log('WebSocket closed');
},
onWebSocketError: error => {
console.error('WebSocket error:', error);
},
onConnect: () => {
console.log('Connected to WebSocket');
client.subscribe('/topic/messages', message => {
const receivedMessage = JSON.parse(message.body);
console.log('[WebSocket] Received message:', receivedMessage);
});
},
onDisconnect: () => {
console.log('Disconnected from WebSocket');
},
onStompError: error => {
console.error('Stomp error:', error);
},
});
client.activate();
setStompClient(client);
return () => {
client.deactivate();
};
}, []);
return (
<View>
<Text>WebSocket Test</Text>
<Button title="send Message" onPress={() => {
if (stompClient && stompClient.connected) {
stompClient.publish({
destination: '/app/send',
body: JSON.stringify({ id: '123', lat: 12.34, lng: 56.78 })
});
} else {
console.warn('STOMP client not connected. Cannot send message.');
}
}}>
</Button>
</View>
)
}
The backend is spring boot , The WebSocket configuration is fine as it works with sample html script and ran on the browser. Can please someone help me in this issue , I have been stuck for long... searched the internet but no luck.
same issue +1, Is there any resolution yet?
Hi , I used brokerURL in place of WebsocketFactory and it worked , please find below the sample code:
import { Client, Versions } from '@stomp/stompjs'; import Config from 'react-native-config';
export let stompClient: Client | null = null;
const socketUrl = ${Config.SOCKET_URL}
//const socketUrl = 'ws://192.168.1.5:8080/ws-location';
// Function to connect to the WebSocket export const connectWebSocket = () => {
if (stompClient && stompClient.connected) { return stompClient; }
console.log("π Connecting to WebSocket at:", socketUrl); stompClient = new Client({ brokerURL: socketUrl, // π use brokerURL, not webSocketFactory stompVersions: new Versions([Versions.V1_2]), forceBinaryWSFrames: true, // Necessary to Android heartbeatIncoming: 4000, heartbeatOutgoing: 4000, logRawCommunication: true, onConnect: () => { console.log('π§© WebSocket connected!'); }, onDisconnect: () => { console.log('STOMP : Disconnected from WebSocket'); }, onStompError: (frame) => { console.error('STOMP error:', frame); }, debug: (msg) => { console.log('STOMP : WebSocket debug:', msg); }, onWebSocketClose: () => { console.log('STOMP : WebSocket closed'); }, onWebSocketError: (error) => { console.error('STOMP : WebSocket error:', error); }, }); console.log("π WebSocket client created:", stompClient); stompClient.activate(); // Start the STOMP client console.log("π WebSocket client activated:", stompClient.connected);
return stompClient; };
export const disconnectWebSocket = () => { if (stompClient) { stompClient.deactivate(); console.log("π WebSocket disconnected."); } };
package.json
"dependencies": { ... "@stomp/stompjs": "^7.1.1", ... },
ThanksοΌI found the issue on my local side β when I set the debug value to undefined, it caused connection problems.