Websocket client disconnects automatically after some time - laravel-4

I am using websockets in my laravel project. I have opened a port by PHP that is 8000 and it is working fine. I am connecting to the port by following in in view file:
function WebSocketInit()
{
if ("WebSocket" in window)
{
// Let us open a web socket
ws = new ReconnectingWebSocket("ws://xxx.xxx.xxx.xxx:8000");
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
WebSocketInit();
ws.onopen = function(){
console.log( "Connected." );
};
ws.onclose = function(){
ws.refresh();
console.log( "Disconnected." );
};
It connects well first time but if I refresh my page then it disconnects and do not re-connect most of the time. Sometimes, it connects but takes few seconds. Any help will be appreciated.
Thanks in advance!

Related

websocket + vue :get error connecting to websocket

I am beginner with websocket and i am trying to connect it with vue3 like this
onMounted(() => {
var connection = new WebSocket("wss://echo.websocket.org");
connection.onopen = function () {
console.log("Server opened");
};
});
and I get this every time
How can I fix this ?
Websocket.org is no longer available.
https://www.lob.com/blog/websocket-org-is-down-here-is-an-alternative

Can't connect to web socket from Electron when using self signed cert

I have an Electron app which tries to connect to a device over a web socket. The connection is encrypted (i.e. wss) but the SSL certificate is self signed and thus, untrusted.
Connecting inside Chrome is ok and it works. However inside Electron I run into problems. Without putting any certificate-error handlers on the BrowserWindow or on the app I receive the following error in the console output:
WebSocket connection to 'wss://some_ip:50443/' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
Then shortly after:
User is closing WAMP connection.... unreachable
In my code, to make the connection I run the following.
const connection = new autobahn.Connection({
realm: 'some_realm',
url: 'wss://some_ip:50443'
});
connection.onopen = (session, details) => {
console.log('* User is opening WAMP connection....', session, details);
};
connection.onclose = (reason, details) => {
console.log('* User is closing WAMP connection....', reason, details);
return true;
};
connection.open();
// alternatively, this also displays the same error
const socket = new WebSocket(`wss://some_ip:50443`);
socket.onopen = function (event) {
console.log(event);
};
socket.onclose = function (event) {
console.log(event);
};
NOTE: Autobahn is a Websocket library for connecting using the WAMP protocol to a socket server of some sort. (in my case, the device) The underlying protocol is wss. Underneath the code above, a native JS new WebSocket() is being called. In other words:
As I mentioned, I've tested this code in the browser window and it works. I've also built a smaller application to try and isolate the issue. Still no luck.
I have tried adding the following code to my main.js process script:
app.commandLine.appendSwitch('ignore-certificate-errors');
and
win.webContents.on('certificate-error', (event, url, error, certificate, callback) => {
// On certificate error we disable default behaviour (stop loading the page)
// and we then say "it is all fine - true" to the callback
event.preventDefault();
callback(true);
});
and
app.on('certificate-error', (event, webContents, link, error, certificate, callback) => {
// On certificate error we disable default behaviour (stop loading the page)
// and we then say "it is all fine - true" to the callback
event.preventDefault();
callback(true);
});
This changed the error to:
WebSocket connection to 'wss://some_ip:50443/' failed: WebSocket opening handshake was canceled
My understanding is that the 'certificate-error' handlers above should escape any SSL certificate errors and allow the application to proceed. However, they're not.
I've also tried adding the following to main.js:
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
});
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = '1';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
With Election, how do I properly deal with a certificate from an untrusted authority? i.e. a self signed cert.
Any help would be much appreciated.
I had the same problem , all i added was your line:
app.commandLine.appendSwitch('ignore-certificate-errors');
I use socket.io, but i think its the same principal.
I do however connect to the https protocol and not wss directly.
This is what my connection looks like on the page:
socket = io.connect(
'https://yoursocketserver:yourport', {
'socketpath',
secure: false,
transports: ['websocket']
});
That seems to have done the trick.
Thank you for the help :) i hope this answer helps you too.

socket.io-client keeping on connecting when using in react-native

I want to use the websocket in my RN project. And I did it using the ws at server side and the RN built-in websocket implementation.
But it seems not so convinient since I use socket.io before.
So I tried to use socket.io:
In RN:
import './userAgent'
import io from "socket.io-client/socket.io"
In component:
componentDidMount() {
this.socket = io('https://localhost:4080',{jsonp: false});
this.socket.on('hello', (msg) =>{
this.setState({response:msg})
});
}
In the server:
io.on('connection', function(socket){
socket.emit('hello','hello world')
console.log('a user connected');
socket.on('disconnect',function(){
console.log('user disconnected')
})
})
And in userAgent.js
window.navigator.userAgent = 'react-native';
That is just the result I googled and they said it will work. But for me, the chrome debugger stopped at:
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
return r;
}
And it says the storage is not defined.
Then I looked into the socket.io.js and find that the exports.storage is window.localStorage. So I disabled the remote js debug, and the code began running.
But the server continues to log : a user connected . as if my RN app is keeping on connecting to the server. And it seems the socket.on() did not work at client side.
react-native version:0.27.2
socket.io-client version:1.4.8
Anyone knows where is going wrong?
Well,finally I found the solution after looking through the socket.io source.
It seems that the socket.io does not use 'websocket' as transport defaultly. It will use the 'polling' in my case, so just explicityly set it :
componentDidMount() {
var socket = io('http://localhost:4080', { jsonp: false, transports: ['websocket'] })
socket.on('hello', (msg) => {
//do something
});
}
Now it works.
But what still confuses me is that in brower client I do not set the transports and it just work well but in react-native it doesn't. Not figured out why.

React Native Websocket Android not connecting to server

I'm trying to use React Native's built in Websocket support. I have this code:
var hostname = "192.168.X.XXX";
var port = "4567";
const webSocket = new WebSocket("ws://" + hostname + ":" + port + "/chat");
and I have this:
componentWillMount: function(){
console.log("MOUNTING CHAT COMPONENT");
webSocket.onopen = function(){
console.log("binding to chat room");
bindToChatRoom();
setTimeout(keepWebSocketOpen, 30000);
ws_connected = true;
};
webSocket.onmessage = function (msg) {
this.handleMsg(msg);
};
webSocket.onclose = function () {
console.log("WebSocket connection closed");
ws_connected = false;
};
webSocket.onerror = function (e){
//add some error handling -> DO THIS
console.log(e.message);
};
},
I'm running a local server using sparkjava, with this:
webSocket("/chat", ChatWebSocketHandler.class);
etc. I've tested the server, and I can connect to it (and send messages) both through both my web browser on my laptop AND on my phone with URL 192.168.x.xxx:4567/chat . However, when I run the react native app, I never see the console message "binding to chat room". Am I missing something? How come this websocket never opens?
Just want to note, I also tried connecting here:
ws://echo.websocket.org
which is described here:
http://www.websocket.org/echo.html
This is a known working websocket, so I know it's purely a react native issue...
Turns out that I had the line of code
const webSocket = new WebSocket("ws://echo.websocket.org");
in the wrong place. If you move it into componentWillMount, it works just fine.

Websocket messages mysteriously disappear

I'm going crazy trying to figure out what's wrong with my system that it is unable to send websocket messages. I've tried a ton of things:
Chrome 32, firefox 27, ie 10
various websocket server libraries: ws, websocket, nodejs-websocket
running the server on windows and centos
reinstalling node.js (to version 0.10.26)
reinstalling firefox
Turning off my firewall
The behavior is always the same: both client and server say they get a connection, but when the client tries to send a message, the other one simply doesn't get it. Sometimes i get "Error: read ECONNRESET" on the server - but not all the time. About 50% of the time it just fails silently. Eventually the connection closes.
If I add code to send a message from the server on connection, it always gets "Error: read ECONNRESET".
What does work?
the exact same code and setup on my laptop
any websocket code online, for example this: http://www.websocket.org/echo.html
So what could cause just my local websocket connection to silently drop messages?
Server:
var
ws = require('websocket').server
var http = require('http')
var server = http.createServer(function(request, response) {
console.log("connection received for "+request.url)
response.writeHead(404)
response.end()
})
server.listen(8080, function() {
console.log("now listening")
})
wsServer = new ws({httpServer:server, autoAcceptConnections: false})
wsServer.on('request', function(request) {
console.log("got request")
var connection = request.accept('a', request.origin)
console.log("got connection")
connection.on('message', function(message) {
console.log("got message: "+message)
})
connection.on("close", function() {
console.log("closed")
})
connection.on('error', function(e) {
console.log('Error: '+e)
})
})
Output:
got connection
closed
Client:
<script>
var ws = new WebSocket('ws://localhost:8080/', 'a')
ws.onopen = function() {
console.log('open')
ws.send('something2')
}
ws.onerror = function(e) {
console.log(e)
}
ws.onmessage = function(m) {
console.log(m)
}
ws.onclose = function() {
console.log('closed')
}
</script>
Output
open
closed
This is driving me crazy.

Resources