0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would like to have a separate channel for each pair of players, but these channels will be created as the two players are connected. Is it possible doing something like this?
You can do something else, make every user connect to his channel. When "Alex" for example sends a message to "Jim", "Jim" will get the message because it listens to the "Jim" channel, and vice-versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.