Отправить данные со стороны браузера на клиентский сервер zeromq node.js - PullRequest
0 голосов
/ 04 октября 2019

У меня есть файл capture.js, включенный в качестве сценария в index.html, который захватывает изображение при нажатии через веб-камеру. Мне нужно отправить base64URL захваченного изображения на клиентском сервере zeromq (клиент TCP), записанном в узле js, чтобы я мог подключиться и отправить его позже на сервер zeromq python (сервер TCP).

Я попыталсямного пути и много раз искал в течение недель, нет ссылки CDN для zeromq и он не может быть скомпилирован, а также переменная показывает undefined в client.js .

Я буду очень признателен, если кто-нибудь поможет мне решить эту проблему. Я вставил текущий код ниже

Это index.html:

 <!doctype html>
<html>
<head>
    <title>WebRTC: Still photo capture demo</title>
    <meta charset='utf-8'>
    <link rel="stylesheet" href="main.css" type="text/css" media="all">
    <script src="capture.js"></script>
    <script src="client.js"></script>
</head>
<body>
<div class="contentarea">
    <h1>
        MDN - WebRTC: Still photo capture demo
    </h1>
    <p>
        This example demonstrates how to set up a media stream using your built-in webcam, fetch an image from that stream, and create a PNG using that image.
    </p>
  <div class="camera">
    <video id="video">Video stream not available.</video>
    <button id="startbutton">Take photo</button> 
  </div>
  <canvas id="canvas">
  </canvas>
  <div class="output">
    <img id="photo" alt="The screen capture will appear in this box."> 
  </div>
    <p>
        Visit our article <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos"> Taking still photos with WebRTC</a> to learn more about the technologies used here.
    </p>
</div>
</body>
</html>

Это capture.js , который запускает веб-камеру исделайте снимок и сохраните base64URL этого образа:

function startWebCam() {


    var width = 320;    // We will scale the photo width to this
    var height = 0;     // This will be computed based on the input stream
    var streaming = false;

    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton = null;

    function startup() {
      video = document.getElementById('video');
      canvas = document.getElementById('canvas');
      photo = document.getElementById('photo');
      startbutton = document.getElementById('startbutton');

      navigator.mediaDevices.getUserMedia({video: true, audio: false})
      .then(function(stream) {
        video.srcObject = stream;
        video.play();
      })
      .catch(function(err) {
        console.log("An error occurred: " + err);
      });

      video.addEventListener('canplay', function(ev){
        if (!streaming) {
          height = video.videoHeight / (video.videoWidth/width);

          // Firefox currently has a bug where the height can't be read from
          // the video, so we will make assumptions if this happens.

          if (isNaN(height)) {
            height = width / (4/3);
          }

          video.setAttribute('width', width);
          video.setAttribute('height', height);
          canvas.setAttribute('width', width);
          canvas.setAttribute('height', height);
          streaming = true;
        }
      }, false);

      startbutton.addEventListener('click', function(ev){
        takepicture();
        ev.preventDefault();
      }, false);

      clearphoto();
    }

    function clearphoto() {
      var context = canvas.getContext('2d');
      context.fillStyle = "#AAA";
      context.fillRect(0, 0, canvas.width, canvas.height);

      var data = canvas.toDataURL('image/png');
      photo.setAttribute('src', data);
    }

    function takepicture() {
      var context = canvas.getContext('2d');
      if (width && height) {
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        var data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);
        sendFromClientJSTestPurpose(data);
      } else {
        clearphoto();
      }
    }

    if (typeof(window) !== 'undefined') {
        window.addEventListener('load', startup, false);
      }
  }

  startWebCam();

Это client.js , который является реализацией клиентской части библиотеки TCP на основе zeromq

// Hello World client
// Connects REQ socket to tcp://localhost:5555
// Sends "Hello" to server.

var zmq = require('zeromq');
 var image64;
// // socket to talk to server
console.log("Connecting to hello world server…");
var requester = zmq.socket('req');

var x = 0;
requester.on("message", function(reply) {
  console.log("Received reply", x, ": [", reply.toString(), ']');
  x += 1;
  if (x === 10) {
    requester.close();
    process.exit(0);
  }
});

requester.connect("tcp://localhost:5555");

for (var i = 0; i < 10; i++) {
  console.log("Sending request", i, '…');
  requester.send("Hello", image64);
}

process.on('SIGINT', function() {
  requester.close();
});


function sendFromClientJSTestPurpose (data) {
  image64 = data;
  console.log('hello world should contain base 64', image64);
}

Это server.py - это реализация Python сервера zeromq, который должен получать base64URL со стороны клиента:

#   Expects b"Hello" from client, replies with b"World"
#

import time
import zmq

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")

while True:
    #  Wait for next request from client
    message = socket.recv()
    print("Received request: %s"  %message)

    #  Do some 'work'
    time.sleep(1)

    #  Send reply back to client
    socket.send(b"World")

Я должен использовать библиотеку zeromq в pythonдля серверной части. Реализация на стороне клиента может варьироваться

Я новичок в программировании на python и сокетах, я буду очень признателен, если вы попытаетесь понять проблему, будьте конкретны и дайте мне плодотворное решение . Спасибо всем заранее. У многих из вас, ребята, есть глубокий уровень знаний и опыта.

...