1 <?php 2 3 $work_path = dirname(__FILE__); 4 chdir($work_path); 5 6 use \Workerman\Worker; 7 use \Workerman\Lib\Timer; 8 9 require_once './Workerman/Autoloader.php'; 10 11 date_default_timezone_set("PRC"); 12 13 // websocket 协议的worker 14 $ws_worker = new Worker('Websocket://0.0.0.0:7011'); 15 // 这里只能写1 16 $ws_worker->count = 1; 17 // websocket server 启动后在当前进程增加一个socket监听 18 $ws_worker->onWorkerStart = function($ws_worker) 19 { 20 // 增加一个Socket端口的监听设备发来的数据 21 $socket_worker = new Worker('tcp://0.0.0.0:7012'); 22 // 当设备发来数据时如何处理 23 $socket_worker->onMessage = function($connection, $data) 24 { 25 // 这里处理设备发来的数据 $data 26 // 比如像这样给所有的WebSocket连接转发数据 27 global $ws_worker; 28 29 if ($data === FALSE) return; 30 31 foreach($ws_worker->connections as $ws_con) 32 { 33 $ws_con->send($data); 34 } 35 }; 36 // 给ws_worker添加一个属性保存socket_worker,方便获取 37 $ws_worker->socketWorker = $socket_worker; 38 // 执行监听 39 $socket_worker->listen(); 40 }; 41 42 // websocket协议也就是浏览器发来数据时 43 $ws_worker->onMessage = function($connection, $data) 44 { 45 // 假设需要转发给所有的设备 46 global $ws_worker; 47 foreach($ws_worker->socketWorker->connections as $socket_con) 48 { 49 $socket_con->send($data); 50 } 51 }; 52 53 Worker::runAll();
欢迎转载,转载请注明:转载自[ http://www.cnblogs.com/zjfree/ ]