简体   繁体   中英

Issues connecting to Node JS websocket using 'connection' keyword

I am setting up a peer to peer server for a blockchain project which leverages the Node JS ws websocket client. For whatever reason, the arrow function in my server.on(...) call does not execute. When I change the keyword to 'listen' however, the function executes. Please help :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(); 

simple syntax error messed me up in line 3.

This...

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

should have been this...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM