mac 开启webSocket服务
2020-10-20 本文已影响0人
冰点雨
1.安装note
2.安装ws
模块
命令
npm install ws
执行结果
ios001@bogon ~ % npm install ws
npm WARN saveError ENOENT: no such file or directory, open '/Users/ios001/package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open '/Users/ios001/package.json'
npm WARN ios001 No description
npm WARN ios001 No repository field.
npm WARN ios001 No README data
npm WARN ios001 No license field.
+ ws@7.3.1
added 1 package from 1 contributor and audited 1 package in 2.827s
found 0 vulnerabilities
3.找到服务端 websocketService.js
程序,这里找到本地文件所在文件夹 执行
node websocketService.js
执行之后就可以监听webSocket了,如下
ios001@bogon iosWebSocket-master % node websocketService.js
开始监听7272端口
client connected
退出连接了
client connected
11111
退出连接了
client connected
11111222
补充一下websocketService.js
就是一个js文件,本地的话自己随便怎么写都行,
下面是我的websocketService.js
文件
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 7272 });
wss.on('connection', function (ws) {
console.log('连接成功');
ws.send('你是第' + wss.clients.length + '位');
//收到消息回调
ws.on('message', function (message) {
console.log(message);
ws.send('收到:'+message);
});
// 退出
ws.on('close', function(close) {
console.log('退出连接了');
ws.send('退出连接');
});
});
console.log('开始监听7272端口');