0
回答
个人业余时间做的P2P文件传输library
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

入口:
https://github.com/edwardwohaijun/simple-filer

技术要求:

  • 客户端暂时只支持Chrome浏览器
  • 服务端需要支持wesocket的webServer即可

安装:

npm install simple-filer

使用:

客户端:

var ws = new WebSocket('wss://127.0.0.1:8443');

var Filer = require('simple-filer')
var filer = new Filer({myID: 123, signalingChannel: ws})

ws.onmessage = msg => {
  var msgObj = JSON.parse(msg.data);
  switch (msgObj.msgType) {
    case "signaling":
      filer.handleSignaling(msgObj);
      break;
  }
};

filer.on('task', function(task) { // when you are about to send/receive a file, newTask event is fired
  console.log('new task: ', task); // this is where you can add task info on the webpage
});

filer.on('progress', function({fileID, progress, fileName, fileURL}){ // file transfer progress event
  console.log('file transfer progress: ', fileName, ': ', progress)
});

filer.on('status', function({fileID, status}){ // file transfer status: pending/sending/receiving/done/removed
  console.log('new status for ', fileID, ': ', status)
});

初始化完filer object后, 定义一些event handlers, 然后当websocket收到message后, 如果是"signaling"的类型, 则丢给filer.handleSignaling(msgObj)去执行即可.

服务端:

wss.on('connection', function(ws){
  ws.on('message', msg => {
    var msgObj = JSON.parse(msg);
    switch (msgObj.msgType) {
      case "signaling":
        var targetClient = users[msgObj.to];
        targetClient.send(msg) // forward the signaling data to the specified user
        break;
      default: console.log('Oops. unknown msg: ', msgObj)
    }
  });
})

WebSocket读取客户端发来的message, 解析后, 如果msgType是"signaling", 则: 转发给"msgObj.to"中指定的接受方.

Example app

通过npm安装后, 目录中附带了一个完整的例子, 只需:

cd node_modules/simple-filer/example
npm install
npm run start

打开Chrome浏览器的2个窗口, 进入 httpS://127.0.0.1:8443  即可实现双方互传文件. 这里有个动态截图显示运行时的界面.

running demo of example app

如果想在本地局域网中运行, 则编辑 example/public/javascripts/bundle.js 文件, 查找 "var ws = new WebSocket", 修改为你的本机IP, 再restart app即可. 要想在你自己的web项目中嵌入该library, 则可以参考 example/public/javascripts/src/demo.js 文件(总共就150行).

遇到问题怎么办

你可以直接在github上提issue, 也可以在本人的chat web app ( http://worksphere.cn/home )上发言(无需注册), 我已经为该simple-filer项目建立了一个讨论组.

<无标签>
举报
华仔Edward
发帖于4个月前 0回/270阅
顶部