gpt4 book ai didi

javascript - 使用 'connection' 关键字连接到 Node JS websocket 时出现问题

转载 作者:行者123 更新时间:2023-12-03 01:22:52 25 4
gpt4 key购买 nike

我正在为一个区 block 链项目设置一个点对点服务器,该项目利用 Node JS ws websocket 客户端。无论出于何种原因,我的 server.on(...) 调用中的箭头函数都不会执行。然而,当我将关键字更改为“listen”时,该函数就会执行。请帮忙:P。

p2p-server.js:

const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.peers ? process.env.PEERS.split(',') : [];

// HTTP_PORT=3002 P2P_PORT=5003 PEERS=ws://localhost:5001,ws://localhost:5002 npm run dev

// HTTP_PORT=3002 P2P_PORT=5002 PEERS=ws://localhost:5001 npm run dev



class P2pServer {
constructor (Blockchain) {
this.blockchain = Blockchain;
this.sockets = [];
}

listen() {
const server = new Websocket.Server({ port: P2P_PORT });
// server.on('connection', socket => this.connectSocket(socket));
server.on('connection', socket => this.connectSocket(socket));

// this.connectToPeers();

console.log(`Listening for peer-to-peer connections on: ${P2P_PORT}`);

}

// connectToPeers() {
// peers.forEach(peer => {
// const socket = new Websocket(peer);

// socket.on('open', () => this.connectSocket(socket));

// });
// }

connectSocket(socket) {

this.sockets.push(socket);
console.log('Socket connected.')
}


}

module.exports = P2pServer;

index.js:

// REST API
const express = require('express');
const bodyParser = require('body-parser');
const BlockChain = require('../blockchain');
const P2pServer = require('./p2p-server');

const HTTP_PORT = process.env.HTTP_PORT || 3001;

const app = express();
const bc = new BlockChain();
const p2pServer = new P2pServer(bc)

app.use(bodyParser.json());

app.get('/blocks', (req, res) => {
res.json(bc.chain);
});

app.post('/mine', (req, res) => {
const block = bc.addBlock(req.body.data);
console.log(`New block added: ${block.toString()}`);

res.redirect('/blocks');
})

app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
p2pServer.listen();

最佳答案

简单的语法错误让我在第 3 行陷入困境。

这个...

const peers = process.env.peers ? process.env.PEERS.split(',') : [];

应该是这样的...

const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];

关于javascript - 使用 'connection' 关键字连接到 Node JS websocket 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51688501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com