WorkerMan 入门学习之(二)基础教程-Connection类的使用
生活随笔
收集整理的這篇文章主要介紹了
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 入门学习之(二)基础教程-Connection类的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Flask 视图
- 下一篇: java多线程总结(二)