PHP websocket连接到node.js服务器



我有一个简单的node.js websocket服务器:

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

可以在JS客户端工作,但不能在PHP客户端工作,例如:

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创建套接字并连接,它不返回任何错误并发送消息,但是node.js服务器没有从这个客户端接收任何东西。我做错了什么?

我不知道var ws = require('../../')是什么,所以我不能评论你做错了什么,但我只是试着做同样的事情,令人惊讶的是它的工作!

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

就是这样!首先启动节点服务器,然后运行PHP脚本。您应该在节点端看到"received Hello World",在PHP端看到" written 11 bytes to socket"。

相关内容

  • 没有找到相关文章