<?php // +-----------------------------------------------------------------------------------------+ // // | 使用WebSocket协议对外提供服务 | // // | 启动方式:/program/php/bin/php /inetpub/wwwroot/workerman/workerman.websocket.php start | // // +-----------------------------------------------------------------------------------------+ // use Workerman\Worker; use Workerman\Connection\TcpConnection; require_once __DIR__ . '/workerman/vendor/autoload.php'; $worker = new Worker('websocket://0.0.0.0:2000'); $worker->count = 4; // 启动4个进程对外提供服务 // 接收到客户端发送过来的消息的回调函数 $worker->onMessage = static function (TcpConnection $connection, $data) { $connection->send("{$data},人生无处不青山。"); // 向客户端发送消息 }; Worker::runAll(); // 运行worker
<!doctype html> <html lang="zh"> <head> <meta charset="utf-8"> <title>workerman使用教程(以WebSocket为例)</title> </head> <body> <script type="text/javascript"> var ws = new WebSocket('ws://192.168.*.*:2000'); // 打开WebSocket后的回调函数 ws.onopen = function () { ws.send('埋骨何须桑梓地'); // 向服务器发送消息 }; // 接收到服务器发过来消息后的回调函数 ws.onmessage = function (e) { console.log(e.data); // 埋骨何须桑梓地,人生无处不青山。 }; </script> </body> </html>
Copyright © 2024 码农人生. All Rights Reserved