我正在尝试编写一个基于Nodejs的简单WebSocket服务器应用程序,但运行npm run dev
时无法启动它。
这是我的package.json
文件:
"name": "lg-chain",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --watchAll",
"dev-test": "nodemon dev-test",
"start": "node ./app",
"dev": "nodemon ./app"
},
"keywords": [],
"license": "MIT",
"devDependencies": {
"jest": "24.1.0",
"nodemon": "1.18.9"
},
"dependencies": {
"body-parser": "1.18.3",
"crypto-js": "3.1.9-1",
"express": "4.16.4",
"ws": "6.1.3"
}
}
我同时开发了http服务器和websocket服务器,我希望它们都将在我运行上述命令时启动。
下面是我的websocket服务器:
const Websocket = require('ws');
const P2P_PORT = process.env.P2P_PORT || 5001;
const peers = process.env.PEERS ? process.env.PEERS.split(',') : [];
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));
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);
});
}
connectSocket(socket) {
this.sockets.push(socket);
console.log('Socket connected');
}
}
module.exports = P2pServer;
这是我的快递服务器:
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.urlencoded({ extended: false }));
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();
我的Express服务器启动了,但是我的Websocket服务器绝对没有任何反应。我在任何地方都没有任何错误。如何开始使用websockets进行故障排除?