我想开发一个应用程序,它从cronjob
(使用PHP
)获取数据并发送到客户端的浏览器。
下一步,我创建一个文件来连接到这个套接字服务器。以下是内容
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = @socket_connect($socket, '127.0.0.1', 8080);
if( $connection ){
echo 'ONLINE';
}
else {
echo 'OFFLINE: ' . socket_strerror(socket_last_error( $socket ));
}
$a = socket_write($socket, 'AAAA');
var_dump($a);
结果显示ONLINE
和4
,但在命令行中未检测到任何连接。 (我多次检查IP和端口,正确)
我不知道遗失或错误的是什么?
抱歉我的英文不好
更新SOCKER服务器脚本
require '/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connections' . "\n"
, $from->resourceId, $msg, $numRecv);
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();