如何在发出成功后侦听新消息(套接字.io在nodej上)?

2024-04-19 11:13:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在最后一次emit(io.sockets.emit)成功后再次侦听新事件(socket.on())。因为,当有很多消息到达节点服务器(socket.on())时,我得到了堆栈溢出(我认为,所有的函数调用都填满了堆栈)。你知道吗

以下是服务器代码(节点):

const path = require('path');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

app.use(express.static('public'));
app.get('/', function(req, res){
    //res.status(200).send("Hola mundo");
    res.sendFile(path.join(__dirname, 'index.html'))
});

io.on('connection',function(socket){
    socket.on('image', function(image){
        io.sockets.emit('image',image);
        return;
    });
});

server.listen(5002, function(){
    console.log("Servidor corriendo en http://localhost:5002");
});

这是客户端代码(python sender to server):

from socketIO_client import SocketIO
import time
import numpy as np
import cv2
import base64

print("Conectando...")
socketIO = SocketIO('localhost', 5002)
cap = cv2.VideoCapture(0)
cap_2 = cv2.VideoCapture(1)
FPS = 23;
print("Conectado.")

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    frame= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    retval, buffer = cv2.imencode('.jpg', frame)
    jpg_as_text = base64.b64encode(buffer)
    socketIO.emit("image",jpg_as_text)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    time.sleep(1/FPS)

cap.release()
cv2.destroyAllWindows()

这是web客户端的代码(来自服务器的接收器):

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <img align="middle" width="1100" height="800" id="image">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
    <script type="text/javascript">
        const socket = io.connect('http://localhost:5002');
        socket.on('image', (data) => {
            const image = document.getElementById('image');
            image.src = `data:image/jpeg;base64,${data}`;
        });
    </script>
</body>
</html>

它用于接收图像并发送到连接的客户端(用于视频),我知道WebRTC,但是,我想了解如何管理函数以避免堆栈溢出。谢谢大家的阅读。你知道吗

以下是节点服务器完全错误:

<--- Last few GCs --->

[2909:0x55b22e73f140]  1832725 ms: Mark-sweep 2687.3 (2800.0) -> 2687.2 (2800.0) MB, 144.5 / 0.0 ms  allocation failure GC in old space requested
[2909:0x55b22e73f140]  1832872 ms: Mark-sweep 2687.2 (2800.0) -> 2687.2 (2769.0) MB, 147.5 / 0.0 ms  last resort GC in old space requested
[2909:0x55b22e73f140]  1833020 ms: Mark-sweep 2687.2 (2769.0) -> 2687.2 (2769.0) MB, 147.6 / 0.0 ms  last resort GC in old space requested


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x3a0332198fe1 <JSObject>
    1: /* anonymous */ [/home/estudiante/Downloads/WebSockets_webCam/node_modules/engine.io/lib/socket.js:~359] [pc=0x254b3a412b24](this=0x4a2f0bec79 <Socket map = 0x1c0e8bebeb61>,data=0x3d8ac82d0021 <Very long string[79045]>,options=0x3d8ac82d0139 <Object map = 0x1c0e8bebdb91>,callback=0x3a0332182241 <undefined>)
    2: arguments adaptor frame: 2->3
    3: writeToEngine [/home/estudiante/Downlo...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [node]
 2: 0x55b22cfe5011 [node]
 3: v8::Utils::ReportOOMFailure(char const*, bool) [node]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [node]
 5: v8::internal::Factory::NewUninitializedFixedArray(int) [node]
 6: 0x55b22cbd1add [node]
 7: v8::internal::Runtime_GrowArrayElements(int, v8::internal::Object**, v8::internal::Isolate*) [node]
 8: 0x254b3a4040bd
Aborted (core dumped)

Tags: ioimageimport服务器nodeonrequiresocket