Sending Data Continuously from Python to Javascript over Websockets?

两盒软妹~` 提交于 2021-01-01 13:37:40

问题


Hello I'm currently running code that sends data from Python to JavaScript. Currently, because I'm not able to send data straight from the primary code I'm running, I am communicating between UDP Connections across two separate Python Files: I merged UDP Server Code with the Main Code I'm running which is an OpenCV Eye Coordinate Tracker. This UDP Server carries the Eye Coordinate data and sends it to the UDP Client which I have merged with the Websocket Server that is communicating with a Javascript Websocket Client.

Simply put, the Data Flow is: (Main Code + UDP SERVER) to (UDP CLIENT + WEBSOCKET SERVER) to WEBSOCKET CLIENT.

While all of this works successfully I have one issue. I need the data to be a continuous stream as it is in the main code. Unfortunately when the Websocket Server receives the data from the Main Code, it just receives and outputs only the first line of data.

How can I get the Websocket to send data as a continuous flow of data as it is in the main code?

Huge Huge Thanks in Advance! This is Part of a huge project and has taken up more time troubleshooting than functioning.

UDP Server + Main Code(OpenCV Gaze Tracker, this is the video I'm using):

import asyncio
import websockets
import cv2
import numpy as np
import math
import socket


UDP_IP = socket.gethostname()
UDP_PORT = 5425
ip_address = socket.gethostbyname(socket.gethostname())

cap = cv2.VideoCapture("EyeMovementZoomed.mp4")

while True:



    ret, frame = cap.read()
    grayVersion = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    grayVersion = cv2.GaussianBlur(grayVersion, (29,29), 0)

    rows, cols, _= frame.shape

    _, threshold = cv2.threshold(grayVersion, 55, 255, cv2.THRESH_BINARY_INV)
    contours = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0] #Keep researching into this, for some reason this failed the first time


    for cnt in contours:
        (x, y, w, h) = cv2.boundingRect(cnt)
        #cv2.drawContours(frame, [cnt], -1, (0, 255,0), 3)
        #cv2.rectangle(frame, (x,y), (x+w, y+h), (0,0,255),1)
        cv2.line(frame, (x + int(w/2),0), (x + int(w/2), rows), (0,255,0), 2)
        cv2.line(frame, (0, y + int(h/2)), (cols, y + int(h/2)), (0, 255, 0),2)
        center_x = (int((1*int(x+w)/2)))
        center_y = (int((2*int(y+h)/2)))
        radius = math.sqrt(w**2+h**2)

        #MESSAGE = str(round((center_x-center_x)+center_x/5))

       # if 132 <= center_x <= 240:
        #    MESSAGE = str(900)
      #  elif 70 <= center_x <= 92:
        #    MESSAGE = str(900)
     #   elif 100 <= center_x <= 172:
   #         MESSAGE = str(500)


        MESSAGE = (str(center_x))

        sock = socket.socket(socket.AF_INET,  # Internet
                             socket.SOCK_DGRAM)  # UDP

       # sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

        sock.sendto(bytes(MESSAGE, "utf-8"), (ip_address, UDP_PORT))




   # cv2.imshow("Gray 2", threshold2)
    cv2.imshow("Threshold", threshold)
    cv2.imshow("Gray Version", grayVersion)
    cv2.imshow("Video", frame)
    key = cv2.waitKey(30)
   # print(center_x)
    print(center_x)

    if key == 27:
        break



cv2.destroyAllWindows()

UDP Client + Websocket Server:

import asyncio
import websockets
import socket

UDP_IP = socket.gethostname()
UDP_PORT = 5425

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:

    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print(str(data))

    async def echo(websocket, path):
        async for message in websocket:
            await websocket.send(str(data)) #FontWeight Value
            print(str(data))



    start_server = websockets.serve(echo, "localhost", 9191)



    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    #loop.run_forever(start_server)

This is the Javascript Client that's receiving:

<html>
   <head>
<title>Adaptive Type Foundry</title>
       <link rel="stylesheet" href="client.css">

      <script type = "text/javascript">


    setInterval( function WebSocketTest() {

            if ("WebSocket" in window) {
              // alert("WebSocket is supported by your Browser!");

               // Let us open a web socket
               var ws = new WebSocket("ws://localhost:5992/echo");

               ws.onopen = function() {

                //   Web Socket is connected, send data using send()
                  ws.send("Message to send");
              //    alert("Message is sent...");

              };


              ws.onmessage = function (evt) {
                  var received_msg = evt.data;
                  var int1 = received_msg.charAt(2)
                  var int2 = received_msg.charAt(3)
                  var int3 = received_msg.charAt(4)

                //  var int1 = received_msg.charAt(7)
                //  var int2 = received_msg.charAt(8)
                //  var int3 = received_msg.charAt(9)


                //  alert("Message is received...");
          //    document.getElementById("demo").innerHTML = evt.data;
              //document.getElementById("demo").innerHTML = parseInt(evt.data,10);
            //  document.getElementById("demo").innerHTML = received_msg.charAt(2)
            //  document.getElementById("demo").innerHTML = received_msg.charAt(3)
                document.getElementById("demo").innerHTML = parseInt(int1.concat(int2, int3))


              document.getElementById("w3review").style.fontWeight = evt.data;
            //  document.getElementById("w3review").style.fontWeight = parseInt(int1.concat(int2, int3));


};



               ws.onclose = function() {

                  // websocket is closed.
                //  alert("Connection is closed...");
               };
            } else {

               // The browser doesn't support WebSocket
               //alert("WebSocket NOT supported by your Browser!");
            }
         }, 1000);

来源:https://stackoverflow.com/questions/62527577/sending-data-continuously-from-python-to-javascript-over-websockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!