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.
Related
I am using socket.io to connect to a different domain, and it can successfully connect using polling, however when attempting to connect using websockets gets the error "WebSocket connection to 'wss://XXXXX' failed".
After observing the network activity the server seems to indicate that it is capable of upgrading to a websocket connection (although I won't claim to be an expert in understanding these requests), but isn't able to do so:
I'm just trying to produce a minimal viable product right now so here is my node.js server code:
let http = require('http');
let https = require('https');
let fs = require('fs');
let express = require('express');
const privateKey = fs.readFileSync('XXXXXXXXX', 'utf8');
const certificate = fs.readFileSync('XXXXXXXXX', 'utf8');
const ca = fs.readFileSync('XXXXXXXXX', 'utf8');
const options = {
key: privateKey,
cert: certificate,
ca: ca
};
let app = express();
let httpsServer = https.createServer(options,app);
let io = require('socket.io')(httpsServer, {
cors: {
origin: true
}
});
httpsServer.listen(443);
console.log('starting');
io.sockets.on('connection', (socket) => {
console.log("something is happening right now")
socket.on("salutations", data => {
console.log(`you are now connected via ${socket.conn.transport.name}`);
socket.emit("greetings", "I am the socket confirming that we are now connected");
});
});
Client-side JavaScript:
const socket = io("https://XXXXXXX");
console.log(socket);
socket.on("connect", () => {
console.log("now connected");
socket.on("message", data => {
console.log(data);
});
socket.on("greetings", (elem) => {
console.log(elem);
});
});
let h1 = document.querySelector('h1');
h1.addEventListener('click',()=>{
console.log("I am now doing something");
socket.emit("salutations", "Hello!");
})
The only suggestion in the official documentation for this issue isn't relevant because I'm not using a proxy, and other suggested fixes result in no connection at all (presumably because they prevent it from falling back to polling)
EDIT: also if it helps narrow down the problem, when querying my server using https://www.piesocket.com/websocket-tester it results in "Connection failed, see your browser's developer console for reason and error code"
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?
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
Here is my code:
var socket = require('socket.io-client')('http://127.0.0.1:3000/printers', {
query: "shop=" + "123456",
transports: ["websocket"]
});
If I delete query, I can connect to socket. Where am I wrong?
There doesn't seem to be anything wrong with your client-side code. I can connect by copying and pasting your code.
I suspect the problem is within your server-side code. Here is an example I am using with your client-side code:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req,res){
res.writeHead(200);
res.end('Hello, World!\n');
});
server.listen(80);
var socket = io.listen(server);
socket.use(function(socket, next){
console.log("Query: ", socket.handshake.query);
if (socket.handshake.query.shop == '123456') {
next();
}
next(new Error('You cannot use that shop'));
});
socket.on('connection', function(client) {
console.log('New Connection');
});
I'm able to obtain the query data in the 'socket.use' function. If I don't call the next() function, the client will never get the message that the server has received the response and is connected.
I recommend checking out the example used in this thread.
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.