Connecting a PHP website to a node.js server

I have a 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)
    })
}

This works with the JS client, but it does not work with the PHP client, for example:

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 a socket and connects, it does not return any errors and a message is sent, but the node.js server does not receive anything from this client. What am I doing wrong? This client works with the websocket PHP server.

+4
source share
1 answer

I don’t know what it is var ws = require('../../'), so I can’t comment on what you are doing wrong, but I just tried to do the same, and surprisingly it works!

Php

<?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;

Node.js

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);

! node, PHP . " Hello World" node " 11 " PHP.

+6

Source: https://habr.com/ru/post/1540891/


All Articles