Answer the question
In order to leave comments, you need to log in
TCP/XML subscription to receive data with NodeJS?
Friends. You need to receive information in real time. With inherently synchronous php, a rather frivolous thing turns out. Started learning NodeJS. But ran into a problem. The system itself works as follows: With its first request, the client announces to the server the
version of the TCP / XML protocol used:
The server reports that it is ready to work with the specified protocol version:
Well, then we also pass the login, password that we need to receive, and the subscribe command and the system upon receipt of the data will from send to us.
So in php it is solved like this:<proto ver="1.0"/>
<proto ver="1.0">OK</proto>
$socket = socket_create(AF_INET, SOCK_RAW, SOL_TCP);
//AF_INET - семейство протоколов
//SOCK_STREAM - тип сокета
//SOL_TCP - протокол
$result = socket_connect($socket, $address, $port);
$msg = '<proto ver="1.0"/>';
echo "Сообщение серверу: $msg\n";
socket_write($socket, $msg, strlen($msg)); //Отправляем серверу сообщение
$out = socket_read($socket, 128); //Читаем сообщение от сервера
var_dump($out);
var net = require('net');
var HOST = '172.16.221.106';
var PORT = 14074;
var loopConnection = function() {
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('<proto ver="1.0"/>');
});
client.on('data', function(data) {
console.log('DATA: ' + data.toString());
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
setTimeout(function() {
loopConnection(); // restart again
}, 1000); // Wait for one second
});
};
loopConnection(); // Initialize and first call loopConnection
Answer the question
In order to leave comments, you need to log in
Something like this should happen?
const net = require('net');
const HOST = '172.16.221.106';
const PORT = 14074;
const client = new net.Socket();
let socketData = '';
let socketWaitHello = true;
client.connect(PORT, HOST);
client.on('connect', () => {
console.log(`CONNECTED TO: ${HOST}:${PORT}`);
client.write(`<proto ver="1.0"/>`);
socketWaitHello = true;
});
client.on('data', (data) => {
socketData += data.toString();
});
client.on('end', () => {
console.log(`DATA: ${socketData}`);
if (socketWaitHello) {
if (socketData === `<proto ver="1.0">OK</proto>`) {
client.write(`<some_auth_data />`);
}
else if (socketData === `<auth_is_accepted />`) {
socketWaitHello = false;
client.write(`<get_some_data />`);
}
else {
throw new Error(`Server don't answered for hello`);
}
}
else {
do_something_with_data(socketData);
}
socketData = '';
});
client.on('close', () => {
console.log(`Connection closed`);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question