使用'connection'关键字连接到Node JS websocket的问题

时间:2018-08-04 18:30:58

标签: javascript node.js websocket blockchain

我正在为一个利用Node JS ws websocket客户端的区块链项目建立对等服务器。无论出于什么原因,我的server.on(...)调用中的arrow函数都不会执行。但是,当我将关键字更改为“侦听”时,该函数将执行。请帮忙: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();

1 个答案:

答案 0 :(得分:0)

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

这个...

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

应该是这个...

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