Reputation: 41
Im trying to "port" some code from PHP into Node and im struggling to find out how to get it working. Im trying too connect to an RCON server over UDP. Here is a simplified version of the PHP version which works:
$address = '1.2.3.4:1234';
$password = 'password';
$socket = stream_socket_client('udp://' . $address, $errno, $errstr);
stream_set_blocking($socket, 0);
$loginRequest = chr(0x45) . $password;
stream_socket_sendto($socket, $loginRequest, 0, $address);
echo 'RCON Login Request Sent' . PHP_EOL;
echo $loginRequest . PHP_EOL;
echo PHP_EOL;
do {
$data = stream_socket_recvfrom($socket, 127, 0, $address);
} while (!$data);
echo 'RCON Received Response' . PHP_EOL;
echo $data . PHP_EOL;
Here is what I have got in Node, which doesnt seem to do anything. I dont even get any acknowledgment of a connection from the server.
var address = '1.2.3.4';
var port = '1234';
var password = 'password';
var socket = require('dgram').createSocket('udp4');
socket.on('message', function (msg, from) {
console.log(msg);
});
socket.on('listening', function () {
var loginPacket = new Buffer(String.fromCharCode(0xff) + password);
socket.send(loginPacket, 0, loginPacket.length, port, address, function (err, bytes) {
console.log('packet sent');
});
});
socket.on('error', function (err) {
console.log('ERROR: ', err);
});
socket.bind(0);
Any help with this would be great! maca134
Upvotes: 2
Views: 2262
Reputation: 106696
The default encoding for passing a string to the Buffer
constructor is not binary
, so you need to pass binary as the encoding: new Buffer('\xFF' + password, 'binary')
. The first 0xFF byte causes issues with the default utf8
encoding. Also, another difference is you're using 0xFF
in node whereas you're using 0x45
in PHP.
Upvotes: 1
Reputation: 38771
socket.bind
takes a port and optional host. You're supplying port 0.
I'm not sure which port you want to listen on but for sake of example I'll use 888.
socket.bind(888);
Upvotes: 0