旗下导航:搜·么
当前位置:网站首页 > PHP框架 > Workerman > 正文

WorkerMan Connection类的运用(附代码)【workerman】

作者:搜搜PHP网发布时间:2019-11-27分类:Workerman浏览:105


导读:下面由workerman教程栏目给人人引见WorkerManConnection类的运用,愿望对须要的朋侪有所协助!一、TcpConnection类的运用...
下面由 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类的运用(附代码)的细致内容,更多请关注ki4网别的相干文章!

标签:WorkerMan