我一边查官网文档一边写的,虽然有send方法,但不知道receive方法在哪,最终还是用emit。
ReceiveService.js
//功能:发送请求并接受文件、保存 const io = require('socket.io-client'); socket = io('http://localhost:3000') const fs = require('fs') //绑定用户终端输入 const readline = require('readline'); const interface = readline.createInterface({ input: process.stdin, output: process.stdout }); let count=0; socket.on('recFile', function (data, filename) { count++; console.log('响应'+count, data) fs.writeFileSync('./Client/' + filename, data) }) interface.on('line', function (input) { console.log('input',input) console.log('您请求了\'' + input + "\'文件。"); socket.emit('fileReq', input) }) interface.on('close', function () { console.log('程序已退出!') })
FileServer.js
//功能:响应请求并发送文件 const fs = require('fs'); //建立web服务器 const app = require('http').createServer(handler) app.listen(3000); console.log(app) const io = require('socket.io')(app) function handler(req, res) { fs.readdir('./Server', function (err, files) { if (err) { console.log(err) res.end('err') } console.log(files) res.end('<meta charset="utf-8">你可以请求这些内容:' + files.toString()) }) //res.end('File Server') } let count=0; io.on('connection', function (socket) { socket.on('fileReq', function (filename) { console.log(filename) fs.open('./Server/' + filename, 'r', function (err, fd) { if (err) { socket.emit('recFile', 'fail') return; } else { fs.stat('./Server/' + filename, function (err, stats) { if (err) { return; } console.log(stats.size) let buf = new Buffer.alloc(stats.size); fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) { console.log(fd) count++; console.log(count) socket.emit('recFile', buf, filename); }) }) } }) }) })