I need to implement websocket connection for my react-native application.
My problem is I always get:
Unable to set ws://www.needseek.com:31337?partyId="a3e75250-d1a3-11e7-9116-a7b8f75cfbc6"&sessionToken="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXJ0eUlkIjoiYTNlNzUyNTAtZDFhMy0xMWU3LTkxMTYtYTdiOGY3NWNmYmM2Iiwibm9uY2UiOiIxNTExNTkxNTQyNDE3MDAiLCJpYXQiOjE1MTE1OTE1NDJ9.HVfHRlXbcUZgkTFfL42YGd0LGtCUjnJuQ5ju3S1alOk" as default origin header.
Here's the code that I used:
let wsUrl = 'ws://www.needseek.com:31337?partyId="' + user.profile.partyId + '"&sessionToken="'+ user.sessionToken + '"';
console.log( 'Websocket Url', wsUrl );
var ws = new WebSocket( wsUrl );
ws.onopen = () => {
// connection opened
ws.send('Connection open..');
console.log('Connection open..');
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
Also, I read the react-native documentation about implementing websocket -> https://facebook.github.io/react-native/docs/network.html
I found the answer. Just use encodeURI() syntax and before passing the websocket url to WebSocket instance.
let wsUrl = encodeURI('ws://www.needseek.com:31337?partyId="' + user.profile.partyId + '"&sessionToken="'+ user.sessionToken + '"');
console.log( 'Websocket Url', wsUrl );
var ws = new WebSocket( wsUrl );
This works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With