以下由workerman教學專欄來介紹WorkerMan Connection類別的使用,希望對需要的朋友有幫助!
一、TcpConnection類別的使用
# 1、簡單的TCP測試
Server.php
<?php require_once __DIR__.'/Workerman/Autoloader.php'; use Workerman\Worker; $worker = new Worker('websocket://0.0.0.0:80');// 连接回调 $worker->onConnect = function ($connection){ echo "connection success\n"; }; // 接受发送消息 $worker->onMessage = function ($conn,$data){ $conn->send("Hello World"); }; // 关闭连接 $worker->onClose = function ($connection){ echo "connection close \n"; }; $worker::runAll();
測試結果:
服務端輸出:
以下錯誤表示,裡面的連線協議沒有修改掉原因。
www@iZ23s8agtagZ:~$ telnet 127.0.0.1 8085 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. ^[[A^[[A HTTP/1.1 400 Bad Request <b>400 Bad Request</b><br>Invalid handshake data for websocket. <br> See <a href="http://wiki.workerman.net/Error1">http://wiki.workerman.net/Error1</a> for detail.Connection closed by foreign host.
2、黑白名單的訪問
Server.php
<?php require_once __DIR__.'/Workerman/Autoloader.php'; use Workerman\Worker; $worker = new Worker('tcp://0.0.0.0:8085'); // 连接回调 $worker->onConnect = function ($connection){ // IP 白名单验证 if($connection->getRemoteIP() != '127.0.0.1'){ $connection->close("IP Address Forbidden"); } }; // 接受发送消息 $worker->onMessage = function ($conn,$data){ $conn->send("Hello World"); }; // 关闭连接 $worker->onClose = function ($connection){ echo "connection close \n"; }; $worker::runAll();
開啟Workerman服務
##正確的訪問: 非本地位址存取:二、 AsyncTcpConnection類別的使用
Server.php<?php require_once __DIR__.'/Workerman/Autoloader.php'; use Workerman\Worker; $worker = new Worker('websocket://0.0.0.0:443'); // Workerman 启动的回调,这里传递的是Worker对象 $worker->onWorkerStart = function ($worker){ echo "onWorkerStart success"; }; // 连接回调 $worker->onConnect = function ($connection){ $connection_baidu = new \Workerman\Connection\AsyncTcpConnection('tcp://www.baidu.com:443'); // 百度的数据发送给浏览器。返回数据后,使用的数据要use 进来, $connection_baidu->onMessage = function ($connection_baidu,$data) use ($connection){ $connection->send($data); }; // 浏览器接受的数据发送给百度 $connection->onMessage = function ($connection,$data) use ($connection_baidu){ $connection_baidu->send($data); }; $connection_baidu->connect(); }; // 接受发送消息 $worker->onMessage = function ($conn,$data){ $conn->send("Hello World"); }; // 关闭连接 $worker->onClose = function ($connection){ echo "connection close \n"; }; //Workerman 停止回调 $worker->onWorkerStop = function ($worker){ echo "onWorkerStop success"; }; $worker::runAll();更多WorkerMan相關文章請關注
WorkerMan使用教學欄位。
以上是WorkerMan Connection類別的使用(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!