I am using NodeJS and SocketIO for my websocket solution. It works fine, but after a few minutes, my socket server always times out with the following messages in my console:
debug - fired heartbeat timeout for client
info - transport end <heartbeat timeout>
debug - set close timeout for client
debug - cleared close timeout for client
debug - discarding transport
Here is my complete server.js file:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(3000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'from socket server' });
socket.on('swipe', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
socket.emit('swipe event received on server!');
});
How can I prevent the timeouts from happening?
Check out the close timeout and heartbeat timeout options here
You can set these programmatically on the server via:
var io = require('socket.io').listen(80);
io.set('close timeout', 60);
io.set('heartbeat timeout', 60);
As for the design of your application, you should check out this question for whether or not you should change the timeout.
Related
Codes based from https://github.com/fireship-io/socketio-minimal-demo/blob/main/server/index.js
Only Version 1 (Websocket version) below works:
wscat -c "ws://localhost:8282"
Connected (press CTRL+C to quit)
> s
< Roger that! s
> f
< Roger that! f
Version 2 & 3 (socket.io version) returns socket hang-up:
wscat -c "ws://localhost:8282"
error: socket hang up
Version 1: Websocket
// server.js
const WebSocket = require('ws')
const server = new WebSocket.Server({ port: '8282' })
server.on('connection', socket => {
socket.on('message', message => {
console.log(message)
socket.send(`Roger that! ${message}`);
});
});
Version 2: socket.io+http
// server.js
const http = require('http').createServer();
const io = require('socket.io')(http, {
cors: { origin: "*" }
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (message) => {
console.log(message);
io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
});
});
http.listen(8282, () => console.log('listening on http://localhost:8282') );
Version 3: socket.io only
// server.js
const options = { /* ... */ };
const io = require("socket.io")(options);
// const io = require("socket.io");
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (message) => {
console.log(message);
// io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
});
});
io.listen(8282);
I run the backend using node server.js
I have also tested the response using Simple Websocket Client extension on chrome I get the same behavior when I test using wscat in the terminal.
Thanks for the tip from Mehmet, I checked the url+params at the dev tools network tab and made it work.
wscat -c "ws://localhost:8282/socket.io/?EIO=4&transport=websocket"
Connected (press CTRL+C to quit)
< 0{"sid":"sSYAv_rKLATxmMEGAAAT","upgrades":[],"pingInterval":25000,"pingTimeout":20000}
< 2
Disconnected (code: 1005, reason: "")
It seems everything should be already working anyway if only I use the socket.io-client js lib to connect (while on html+javascript).
When I used command-line wscat, I did not know that there should be parameters in the url when using socket.io
The fix was simple after I checked the url+params the socket.io client is using to connect to the server (visible at chrome devtools network tab).
My server code:
var io = require('socket.io')(3000, {
cors: {
origin: '*',
},
});
io.sockets.on('connection', function(socket) {
.........
});
My client code:
var socket = io.connect('localhost:3000');
socket.on('connect', function() {
console.log(socket);
socket.emit('init', 'Hello');
});
When I start the browser with client page and immediately after connection I'm receiving socket object in the console, but not anytime socket.emit is happening when looking into Network/WS tab in Dev tools.
Whats wrong?
Getting error on execution of Lambda, In Lambda(Client WS), trying to establish connection and send messages on Websocket server hosted on EC2.
If i reboot EC2 then, only first time Lambda runs successfully and server receives message but subsequent Lambda calls fails with error "Time out in 3 sec"
// Node JS --- Hosted on EC2
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8085 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
});
ws.send(JSON.stringify({status:'Connected'}));
// Lambda
const WebSocket = require('ws');
const ws = new WebSocket('ws://ec2-public-ip.com:8085');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
Getting Error : Time out in 3.xx sec
Thank You!
I am trying to send a string to the client like this:
socket.emit("start", "calm");
but it is throwing an error, is it because it is not an object ?
First thing first, you should make sure your socket between server-side and client-side is connect. And register event and function to the socket.
Server-side
io.sockets.on('connection', function(socket) {
console.log('socket connect' + socket.id);
// when a client connect to server within socket, server will send hello
io.emit('newMsg', "hello")
socket.on('disconnect', function() {
console.log('socket disconnect');
})
// when server receive a message, it will send to all client which connect
to the server
socket.on('data', function (data) {
console.log(socket.id +': ' + data.msg);
var message = {from: socket.id,
msg: data.msg
}
io.emit('newMsg', message)
})
}
Client-side
var socket = io('http://localhost:3000');
socket.on('connect', function (data) {
console.log(data)
})
socket.on('newMsg', function(data) {
console.log(data)
})
// function could bind on button on client side page, get input and send data
function sendData() {
var input = document.getElementsByTagName('input')
var text = input[0].value
var data = { msg: text }
socket.emit('data', data)
}
open console, the information would show in the console. When sending a message on server-side, could use 'broadcast' instead of 'emit' as well to send the message to other clients except you. Read the doc: socket.io doc
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.