socket.io 与 node.js /express.js 出现问题

发布于 2024-12-10 12:27:53 字数 1016 浏览 0 评论 0原文

我正在玩一下node.js 和socket.io。这是我正在编写的代码:

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

一切都已正确导入。 gameId 已正确设置,io 变量已正确初始化。 运行此代码时(尝试访问 localhost/play 时),我收到此错误:

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)

如果我注释掉 var gameMessage 代码行,则不会收到错误。这就是生成它的原因。

我希望该行保留在那里,因为它正在实例化我需要的通道。这样两个人就可以一起玩我的游戏了。如果我不实例化它并尝试在客户端运行一些代码,就像

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

第二个玩家连接时在控制台中出现无限循环错误一样。

有人能猜出这有什么问题吗?谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贱贱哒 2024-12-17 12:27:53

你所做的事情是错误的,你不应该将 Socket.IO 代码放入你的路由中,Express.js 应用程序和 Socket.IO 应用程序不会像这样“连接”。

使用 Socket.IO 服务器创建一个单独的文件,然后在以下情况下使用 socket.io-client例如,您想要连接到 Socket.IO(从服务器端或客户端)来发送消息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文