【发布时间】:2020-10-05 19:44:32
【问题描述】:
我正在尝试使用递归函数从客户端向我的服务器无限发送数组并相应地从我的服务器获得响应,但是来自我的服务器的消息不会实时返回,它只是在递归函数之后被终止来自服务器的消息被发送。
我不确定是客户端的代码问题还是服务器端的代码问题。提前致谢。
这是我的 server.js 脚本。
var express = require('express');
var app = express();
var https = require('https').createServer(sslOptions, app);
var io = require('socket.io')(https);
const port = 8080;
const host = "x.x.x.x"; // my host server IP address
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('predict', (data)=>{
// this line is executed after recursive function at client side is stopped
console.log("socket from client");
// this line is executed after after recursive function at client side is stopped
socket.emit('result', { "message": "hello world from server"});
});
});
https.listen(port, host);
这是我的 app.component.ts 脚本。
// this is my recursive function
detectFromVideoFrame = (model, video, stop_detecting) => {
this.detect(video).then(predictions => {
// stop recursive loop if stop_detecting == true
if(!(this.stop_detecting)){
requestAnimationFrame(() => {
this.detectFromVideoFrame(model, video, stop_detecting);
});
}
}, (error) => {
console.error(error)
});
};
this.dataService.setupSocketConnection();
// these two lines are in this.detect function
this.dataService.getTFprediction(imageTensorArr);
this.dataService.onNewMessage().subscribe(msg => {
console.log('got a msg: ', msg);
});
这是我的 service.ts 脚本
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import * as io from 'socket.io-client';
@Injectable({
providedIn: 'root'
})
export class DataService {
private socket: SocketIOClient.Socket;
constructor() {}
setupSocketConnection() {
this.socket = io('https://x.x.x.x:8080');
this.socket.on('connect', function () {
console.log("socket connected on client side");
});
}
getTFprediction(videoArray){
// this line is executed normally each time this function is called at the app.component.ts script
console.log("check connection: ", this.socket.connected);
// I'm not sure when is this line executed
this.socket.emit('predict', { "data": videoArray } )
}
onNewMessage() {
return Observable.create(observer => {
this.socket.on('result', msg => {
console.log(msg.message);
observer.next(msg);
});
});
}
}
【问题讨论】:
标签: javascript node.js angular express socket.io