I have a Node JS app using Socket.io deployed to heroku. I have followed the steps provided at https://devcenter.heroku.com/articles/node-websockets to setup the code properly but somehow it seems like I am unable to use Web sockets properly.
All my socket polling requests are failing with the following error.
{"code":1,"message":"Session ID unknown"}
The same code seems to be working fine when I run it locally.
Client
function createSocket() {
socket = io();
socket.on('connect', function () {
socket.emit('registerUser', { userEmail: $scope.userInfo.userEmail });
});
socket.on('list_of_files', function (data) {
$timeout(function () {
$scope.fileList = data;
});
});
}
Server
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
socket.on('registerUser', function (data) {
socketClients[data.userEmail] = socket;
});
});
I have also enabled heroku's session affinity but still no luck
i know its too late but for those who still looking for the answer try adding this option on the client socket.
{
path: '/socket.io',
transports: ['websocket'],
secure: true,
}
also just for your information i'm having this problem after deploying to staging server with nginx and proxy
Same question on iOS platform, "session id unknown ..."
before
[[SocketIOClient alloc] initWithSocketURL:url config:#{#"log": #NO, #"forcePolling":#YES, #"reconnectWait":#1}];
after
[[SocketIOClient alloc] initWithSocketURL:url config:#{#"log": #NO, #"forcePolling":#YES, #"forceWebsockets":#YES}];
Related
Server code:
import http from 'http';
import Koa from 'koa';
import { Server } from 'socket.io';
(async () => {
const app = new Koa();
var server = http.createServer(app.callback());
var io = new Server(server, {
path: '/seacher',
transports: ['websocket'],
});
io.on('connection', (socket) => {
setTimeout(() => socket.emit('message', { say: 'hello' }), 1000);
socket.on('message', (msg) => {
console.log('[msg]', msg);
});
});
server.listen(3000)
})();
Client code:
var socket = io('http://localhost:3000/seacher', {
path: '/seacher',
autoConnect: false,
transports: ['websocket'],
});
socket.on('error', (err) => console.log('error', err));
socket.on('connect', () => console.log('connect'));
socket.connect();
No any messages in browser / nodejs console.
In the Network tab in browser a lot of connections with messages like
Change the client code to this:
var socket = io('http://localhost:3000', { // note changed URL here
path: '/seacher',
autoConnect: false,
transports: ['websocket'],
});
The path option specifies what URL socket.io is going to use internally. You put that in the path option as you have already done in both client and server.
If you put something in the URL you specify like you had 'http://localhost:3000/seacher', then that is the namespace /seacher that you are trying to connect, but your server does not support that namespace.
This is a confusing part of socket.io's design, but path and namespace are not the same thing in socket.io. Do not confuse or mix them.
FYI, there is rarely a reason to customize the path option the way you have done unless you are trying to run more than one socket.io server shared on the same http server (something it does not appear you are doing). By default, the path is /socket.io which makes a lot of sense in logs and debuggers and when accessing the client-side library. I would suggest you remove the path option from both client and server and let it default to /socket.io. And, don't use a path in your connection URL either as that specifies a namespace, not a path.
I have a problem w my Node Server + Socket Client.
Well, my localhost server works perfect.
But... when i connect my socket.io client (node) w my external server (ex: www.myserver.com:3000) doesnt works.
I dont recieve any data. (message var)
This is my sample code:
var io = require("socket.io-client");
var requestHTTP = require("request");
var socket = io('http://myserver.com:3000');
var room = "game881";
console.log('test simple socket '+room+'');
socket.on('news', function (data) {
console.log(data);
socket.emit('conectado', { my: 'Conectado!' });
});
socket.on('connect', function () {
socket.emit('room', room);
console.log('Conectando a ' + room);
});
socket.on('message', function (data) {
var json = data.message;
json = JSON.parse(json);
console.log(json);
});+
Why dont recieve any data?
CORS? I've already tried.
Port used?
:) thanks!
Well... i solved my problem.
I use this.
Setup Server-Server SSL communication using socket.io in node.js
The previous answers didn't do it for me. require('https').globalAgent is always >undefined.
Did some seaching and found the rejectUnauthorized parameter in the docs (https://nodejs.org/api/tls.html). Not sure if it's related to SocketIO, but it somehow seems to work with self-signed certificates:
var socket = io.connect('//yourhost:8000', {secure: true, rejectUnauthorized: false})
secure: true might be optional, but I like to enforce it anyhow.
It is simple chat app using node.js and socket.io. This app work fine in my local computer but do not work when I upload it to the server: Please look at my code on remote server and the problem.
Here is the code snippet of client:
<script type="application/javascript">
var socket = io.connect();
eventHandler(socket);
function eventHandler(socket) {
socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
});
socket.on('error', function () {
console.log("Connection error"); //It works after a few second with error
});
}
$(document).ready(function(){
.....
});
</script>
It looks like on the remote server Socket.IO 0.9.16 is installed (which is not up-to-date). If you're writing code according to new documentation this might be a reason why it doesn't work as you expected.
Try to upgrade Socket.IO to 1.0
This change worked for me:
you wrote this method:
var socket = io.connect();
Thanks to another help page, I switched this method to this:
var socket = io.connect('http://localhost:8080');
You can replace "localhost" with whatever ip address you use to access your server.
Also, just in case - if you haven't, it would be useful to include a connection notification on your server in the app.js file. mine looks like the following:
var fs = require("fs")
, http = require("http")
, socketio = require("socket.io");
var server = http.createServer(function(req, res) {
res.writeHead(200, { "Content-type": "text/html"});
res.end(fs.readFileSync(__dirname + "/index.php"));
}).listen(8080, function() {
console.log("Listening at http://localhost:8080");
});
socketio.listen(server).on("connection", function(socket) {
console.log("CONNECTED");
socket.on("message", function(msg) {
console.log("Message received: ", msg);
socket.broadcast.emit("message", msg);
});
});
You can also see the help page I linked to in case they have something that more closely relates to your issue.
Your page seems to be working for me. Make sure your page is fully loaded before executing your script. This is done by using window.onload like this:
<script>
window.onload = function() {
//Your code here
}
</script>
I am trying to connect to a third party socket.io site with Node.js. I have installed socket.io-client. However, when I type "node script.js", it terminates after a split second.
This is my pretty simple code:
var io = require('socket.io-client');
socket = io.connect('https://just-dice.com/', {secure: true});
socket.on('connect', function(){
console.log("HI");
socket.on('chat', function(txt, date) {
console.log(txt);
});
});
Why is it terminating?
I'd start by seeing if socket.io is throwing any errors:
socket.on('error', function (exception) {
console.log(exception);
});
I'd also look to see if you're connecting to the right port. It's probable that the remote socket.io server is not on a default port.
I'm trying to create a test using LearnBoost's socket.io and the node-websocket-client. Communication between the client and server work great. After all communication is done, I close both the client and the server. Yet the program hangs, waiting on some unknown callback. Two questions:
What is the following program waiting for?
Is there a tool for diagnosing outstanding callbacks in node programs?
var connect = require('connect'),
io = require('socket.io'),
WebSocket = require('websocket-client').WebSocket;
var port = 7111;
var server = connect.createServer();
var socket = io.listen(server);
socket.on('connection', function(client) {
client.send('Welcome!');
client.on('message', function(message) {
console.log(message);
});
client.on('disconnect', function() {
console.log('closing');
server.close();
});
});
server.listen(port, function() {
var ws = new WebSocket('ws://localhost:' + port + '/socket.io/websocket');
ws.onmessage = function(message) {
console.log(message.data);
};
setTimeout(function() {
ws.send('~m~3~m~Yo!');
ws.close();
}, 10);
});
EDIT: changed the variable name of the WebSocket to ws to avoid confusion
var socket = io.listen(server);
You've created a socket on a port. You've never closed it.
socket.server.close() closes your (socket.io) socket.
When in doubt read the socket.io github examples
socket.server === server It's the server you pass in, in the liste statement so it's closed. I'm not sure what it's waiting for.
Below a way to shutdown all the connections and be able to run multiple expresso tests (using socket.io and socket.io-client).
The solution is tricky and buggy but works on 0.8.5. The main problem is regarding the library to use websockets (node-websocket-client).
Currently, on socket.io, the OS contributors have patched the websocket client. So, we must do the same on our socket.io-client npm package to be able to use finishClose method on the socket client side. Socket.io-client uses the websocket library as npm package, so you must find the file (websocket.js) and substitute it with the same on socket.io.
Afterwards, you could use finishClose method to ensure the connections are closed and with some custom server/client socket settings, the tests will run correctly.
var io = require("socket.io").listen(port);
io.set('close timeout', .2);
io.set('client store expiration', .2);
var client = require("socket.io-client").connect( "http://localhost", { port: port , 'reconnect': false, 'force new connection': true});
client.on('connect', function() {
client.disconnect();
});
client.on('disconnect', function() {
client.socket.transport.websocket.finishClose();
io.server.close();
});
io.server.on('close', function() {
setTimeout( function() {
done();
}, 500);
});
Hope, somebody can help.
The program is waiting because socket.io (server) is still listening for incoming connections. I don't know of any way to stop listening.