Мне нужна функция, которая может вызывать удаленный синхронно
- отправить сообщение
дождаться получения удаленного ответа, например (Object.wait () или CountDownLatch.wait () в Java
3.При получении сообщения установите ответ
, но проблема в том, как «подождать»? Я пробовал следующий код:
import * as http from 'http'
import * as ws from 'websocket';
export class DevicesServer {
private httpServer: http.Server;
private response: string | undefined = undefined;
private connection: ws.connection | undefined = undefined;
startServer(port: number) {
this.httpServer = http.createServer(function (request, response) {
console.log(new Date() + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
var wsServer = new ws.server({ httpServer: this.httpServer });
wsServer.on('request', request => {
console.log(`new connection: ${request}`);
this.connection = request.accept();
this.connection.on("message", (data) => {
console.log(`receive ${request}`);
this.response = data.utf8Data;
})
this.syncRemoteCall();
})
this.httpServer.on('error', (e) => {
console.error('server error: ', e);
});
this.httpServer.listen(port, '0.0.0.0', () => {
let address = this.httpServer.address();
console.log(`server started on ${JSON.stringify(address)}`);
});
}
/** this is the problem, I want to send a request and the function
do not return and wait until the response is received, but if
wait like this, the connection is likely paused,and cannot receive any data */
syncRemoteCall(): string {
console.log(`syncRemoteCall start `);
this.connection.sendUTF(`{"message":"hello is am server"}`);
while (this.response == undefined) {
// how to wait some time until this.response have data?????
new Promise(resolve => setTimeout(resolve, 100));
}
console.log(`syncRemoteCall ok response=${this.response} `);
return this.response;
}
}
let server = new DevicesServer()
server.startServer(8888);
console.log("started on 8888")
** Есть ли способ реализовать метод syncRemoteCall? **