Masiar
Masiar

Reputation: 21352

socket.io giving issue with node.js / express.js

I'm playing a bit with node.js and socket.io. This is the piece of code I'm writing:

app.get('/play', function (req, res) {
//some code you don't need to see
var gameMessage = io.of('/game'+gameId);
});

Everything is imported correctly. gameId is correctly set and the io variable is correctly initialized. When running this code (when trying to access localhost/play) I get this error:

TypeError: Converting circular structure to JSON
    at Object.stringify (native)
    at Array.<anonymous> (/path/to/my/game/node_modules/express/node_modules/connect/lib/middleware/session/memory.js:74:31)
    at EventEmitter._tickCallback (node.js:126:26)

If I comment out the var gameMessage line of code, I don't get the error. So that's generating it.

I would like that line to stay there because it's instantiating a channel that I need. In this way two people can play together my game. If I don't instantiate that and try to run some code in the client side like

var chat = io.connect('http://localhost/chat' + gameId);
        chat.emit('guess', {
            guess: "ciao"
        });
        chat.on('guess', function (data) {
            alert(data);
        });

I get an infinite loop of error in the console as the second player connects.

Can someone guess what's wrong with this? Thanks.

Upvotes: 0

Views: 629

Answers (1)

alessioalex
alessioalex

Reputation: 63653

What you're doing is wrong, you shouldn't put that Socket.IO code into your route, Express.js apps and Socket.IO apps don't "connect" like that.

Make a separate file with your Socket.IO server, then use socket.io-client when you want to connect to Socket.IO (from the server side OR client-side) to send a message for example.

Upvotes: 1

Related Questions