通过本地网络在两个node.js应用程序之间进行简单通信

时间:2018-12-28 13:59:27

标签: node.js networking localhost

我正在编写同时在笔记本电脑和PC上运行的应用程序(使用NWjs)。如果仅想通过我的应用在两台计算机之间交换一些数据,该怎么办?

想法是:

  • Machine1(192.168.1.35):这是我可以播放的文件
  • Machine2(192.168.1.36):我被该文件干扰了
  • Machine1(192.168.1.35):好的,我在192.168.1.35:3000/0上播放

我当时正在考虑使用Machine1托管的json文件(如192.168.1.35:3000/db.json)公开“我可以播放的文件”

然后,使用Machine2读取json,选择一个文件,然后???沟通???是Machine1的哪一个。

然后,Machine1将其托管在192.168.1.35:3000/0上,并且???沟通??? Machine2的完整路径。

“ ???沟通???”部分是我被卡住的地方。我可以使用一些简单的方法吗?也许类似于“ net send” windows命令(以及我可以实际读取已发送内容并相应采取措施的部分)。

谢谢。

2 个答案:

答案 0 :(得分:1)

您需要在一台机器(例如机器A)上运行HTTP(Node.js)服务器,以便可以从另一台机器(从Node.js应用程序,机器B)发出HTTP请求,从而在机器之间进行通信。您将必须在计算机A的应用程序上公开HTTP请求端点。一些不错的库是

  • ExpressJS

  • RESTify

最重要的是,您可以在两台机器的Node.js应用程序上建立WebSocket接口,以实现基于事件的更快通信。

答案 1 :(得分:0)

经过一些挖掘,事实证明您可以POST到http服务器。这是我所做的:

Machine1:

public void initDagger(){
getApplication().getAppCompoment().inject(this);
}

Machine2:

let ip = '192.168.1.35';

// create a json
let json = {
  movies:[
    {title: 'my movie 1',
     path: 'D:\Videos\mymovie1.mkv,
     size: 100000},
    {title: 'my movie 2',
     path: 'D:\Videos\mymovie2.mkv,
     size: 100000}
  ]
};

// create a server for GET/POST
let apiServer = require('http').createServer((res,req) => {

  // on GET, serve the json
  if (req.method === 'GET') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.write(JSON.stringify(json));
    res.end();
  }

  // on POST, check what the Machine2 wants to play
  if (req.method === 'POST') {
    let body = String(); // create body
    req.on('data', data => body += data); // update body with POST content

    req.on('end', () => {
      let file = JSON.parse(body);

      // create a server for serving the file over http
      let playServer = http.createServer((req,res) => {
        res.writeHead(200, {
          'Content-Type': 'video/mp4',
          'Content-Length': file.size
        });

        let readStream = require('fs').createReadStream(file.path);
        readStream.pipe(res);
      });

      // start serving the file on localhost:3001
      playServer.listen(3001);

      // respond to Machine2 where the file is streamed
      res.writeHead(200, {'Content-Type': 'application/json'});
      res.write(JSON.stringify({
        url: `http://${ip}:3001`
      }));
      res.end();
    });
  }
});

// start serving the json on localhost:3000
apiServer.listen(3000);
相关问题