1.新建文件夹
2.使用终端 npm init 创建packjson
{
"name": "ws",
"version": "1.0.0",
"description": "",
"main": "stream.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ws": "1.1.1"
}
}
3.下载依赖 npm install
4.npm start 启动项目
新建app.js
代码如下:
const WebSocket = require('ws'); const WebSocketServer = WebSocket.Server; const wss = new WebSocketServer({ port: 3000 }); wss.on('connection', function (ws) { console.log(`[SERVER] connection()`); ws.on('message', function (message) { console.log(`[SERVER] Received: ${message}`); setTimeout(() => { ws.send(`What's your name?`, (err) => { if (err) { console.log(`[SERVER] error: ${err}`); } }); }, 1000); }) }); console.log('ws server started at port 3000...'); // client test: let count = 0; let ws = new WebSocket('ws://localhost:3000/ws/chats'); ws.on('open', function () { console.log(`[CLIENT] open()`); ws.send('Hello!jiaojiao.liu'); }); ws.on('message', function (message) { console.log(`[CLIENT] Received: ${message}`); count++; if (count > 5) { ws.send('Goodbye!'); ws.close(); } else { setTimeout(() => { ws.send(`Hello, I'm Mr No.${count}!`); }, 2000); } });
node app.js
代码如下