hi,你好!欢迎访问本站!登录
本站由简数采集腾讯云宝塔系统阿里云强势驱动
当前位置:首页 - PHP框架 - Workerman - 正文 请牢记本站网址www.sosophp.cn

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

2019-11-27Workerman搜搜PHP网54°c
A+ A-
下面由 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网别的相干文章!

  选择打赏方式
微信赞助

打赏

QQ钱包

打赏

支付宝赞助

打赏

  选择分享方式
  移步手机端
WorkerMan Connection类的运用(附代码)【workerman】

1、打开你手机的二维码扫描APP
2、扫描左则的二维码
3、点击扫描获得的网址
4、可以在手机端阅读此文章
标签: