I have simple node.js websocket server:
var fs = require('fs')
var ws = require('../../')
var options = {
secure: false,
}
var Server = ws.createServer(options, function(conn){
conn.on("text", function (str) {
broadcast(str);
//conn.sendText(str.toUpperCase() + "!!!")
console.log('connected');
console.log(str);
//console.log(Server.connections);
})
}).listen(8001, "127.0.0.1");
function broadcast(str){
Server.connections.forEach(function (connection) {
connection.sendText(str)
})
}
That works with JS client, but it doesn't work with PHP client, such as:
function MaskMessage($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
$host = 'localhost';
$port = 8001;
$msg = 'hey hi hello';
$msg = MaskMessage('hej hej siema');
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Bind the source address
$result = socket_connect($socket, $host, $port);
if(!$result)
echo 'cannot connect '.socket_strerror(socket_last_error());
else{
echo socket_write($socket, strval($msg), strlen($msg));
}
socket_strerror(socket_last_error());
socket_close($socket);
PHP creates socket and connects, it doesn't return any errors and message is sent, but node.js server doesn't receive anything from this client. What am I doing wrong? This client works with PHP websocket server.
I don't know what var ws = require('../../')
is, so I can't comment on what you're doing wrong, but I just tried doing the same thing, and surprisingly it works!
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 1337);
if(!$result) {
die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
}
$bytes = socket_write($socket, "Hello World");
echo "wrote ".number_format($bytes).' bytes to socket'.PHP_EOL;
var net = require('net');
var server = net.createServer();
var host = '127.0.0.1';
var port = 1337;
server.on('listening', function() {
console.log('listening on '+host+':'+port);
});
server.on('connection', function(socket) {
socket.on('data', function(buf) {
console.log('received',buf.toString('utf8'));
});
});
server.listen(port, host);
That's it! Start the node server first, then run the PHP script. You should see "received Hello World" on the node side, and "wrote 11 bytes to socket" on the PHP side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With