찾다
PHP 프레임워크Workerman메시지 푸시에 Workererman을 사용하는 방법

다음 칼럼에서는 workerman Tutorial에서 Workerman을 사용하여 메시지를 푸시하는 방법을 소개하겠습니다. 필요한 친구들에게 도움이 되길 바랍니다!

메시지 푸시에 Workererman을 사용하는 방법

Workerman은 순수하게 PHP로만 개발된 오픈 소스 고성능 PHP 소켓 서버 프레임워크입니다. 모바일 앱, 모바일 통신, WeChat 애플릿, 모바일 게임 서버, 온라인 게임, PHP 채팅방, 하드웨어 통신, 스마트 홈, 차량 인터넷, 사물 인터넷 및 기타 분야의 개발에 널리 사용됩니다.

TCP 긴 연결을 지원하고 Websocket, HTTP 및 기타 프로토콜을 지원하며 사용자 정의 프로토콜을 지원합니다. 비동기 Mysql, 비동기 Redis, 비동기 Http, 비동기 메시지 대기열 등과 같은 많은 고성능 구성 요소가 있습니다. 비슷한 것으로는 swoole과 MeepoPS가 있습니다.

먼저 Workererman의 웹 메시지 푸시 시스템 web-msg-sender를 다운로드하세요.

# wget http://www.workerman.net/download/senderzip
# unzip senderzip
#cd web-msg-sender 
#vim start.php
use Workerman\Worker;
// composer 的 autoload 文件
include __DIR__ . '/vendor/autoload.php';
if(strpos(strtolower(PHP_OS), 'win') === 0)
{
    exit("start.php not support windows, please use start_for_win.bat\n");
}
// 标记是全局启动
define('GLOBAL_START', 1);
// 加载IO 和 Web
require_once __DIR__ . '/start_io.php';
可以注释掉 webServer 服务 没什么用  省点资源
// require_once __DIR__ . '/start_web.php';
// 运行所有服务
Worker::runAll();

Save

#vim start_io.php
找到 将端口改成你要监听的端口 我是2120 记住要在安全组里入方向添加白名单
// PHPSocketIO服务 
$sender_io = new SocketIO(2120);
服务端设置完毕后
#php start.php start -d //开启服务 并保持进程

Push 클래스 저는 tp5를 사용합니다

<?php
namespace app\index\moudel; 
/**
 * 推送事件
 * 典型调用方式:
 * $push = new WebSocket();
 * $push->setUser($user_id)->setContent($string)->push();//连贯操作
 *
 * Class WebSocket
 * @package app\index\moudel; 
 */
class WebSocket
{
    /**
     * @var string 目标用户id
     */
    protected $to_user = &#39;&#39;;
    /**
     * @var string 推送服务地址 
     */
    protected $push_api_url = &#39;http://127.0.0.1:2000&#39;;
    /**
     * @var string 推送内容
     */
    protected $content = &#39;&#39;;
    /**
     * 设置推送用户,若参数留空则推送到所有在线用户
     *
     * @param string $user
     * @return $this
     */
    public function setUser($user = &#39;&#39;)
    {
        $this->to_user = $user ? : &#39;&#39;;
        return $this;
    }
    /**
     * 设置推送内容
     *
     * @param string $content
     * @return $this
     */
    public function setContent($content = &#39;&#39;)
    {
        $this->content = $content;
        return $this;
    }
    /**
     * 推送
     */
    public function push()
    {
        $data = [
            &#39;type&#39; => &#39;publish&#39;,
            &#39;content&#39; => $this->content,
            &#39;to&#39; => $this->to_user,
        ];
        // var_dump($data);
        // var_dump($this->push_api_url);
        $ch = curl_init ();
        curl_setopt($ch, CURLOPT_URL, $this->push_api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(&#39;Expect:&#39;));
        $res = curl_exec($ch);
        curl_close($ch);
        dump($res);
    }
}

조작 컨트롤러

<?php
namespace app\index\controller;
use think\Controller;
use app\index\moudel\WebSocket;
class Index extends Controller
{
 /**
     * 推送一个字符串
     */
    public function push_msg(){
        $uid = input(&#39;uid&#39;,&#39;&#39;);//uid为空的时候推送给所有用户
        $string = &#39;这是一个推送的测试&#39;;
        $string = input(&#39;msg&#39;) ? : $string;
        $push = new WebSocket();
        $push->setUser($uid)->setContent($string)->push();
    }
    /**
     * 推送目标页
     *
     * @return \think\response\View
     */
    public function targetPage(){
        return view();
    }
}

푸시 대상의 프런트엔드 표시

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<strong id="count"></strong>
<h1 id="target"></h1>
</body>
</html>
<script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
<script src=&#39;http://cdn.bootcss.com/socket.io/1.3.7/socket.io.js&#39;></script>
<script>
    jQuery(function ($) {
        // 连接服务端
        var socket = io(&#39;http://39.106.132.216:2000/&#39;); //这里当然填写真实的地址了
        // uid可以是自己网站的用户id,以便针对uid推送以及统计在线人数,但一定是唯一标识
        uid = 321;
        // socket连接后以uid登录
        socket.on(&#39;connect&#39;, function () {
            socket.emit(&#39;login&#39;, uid);
        });
        // 后端推送来消息时
        socket.on(&#39;new_msg&#39;, function (msg) {
            console.log("收到消息:" + msg);
            $(&#39;#target&#39;).append(msg).append(&#39;<br>&#39;);
        });
        // 后端推送来在线数据时
        socket.on(&#39;update_online_count&#39;, function (online_stat) {
            console.log(online_stat);
            $(&#39;#count&#39;).html(online_stat);
        });
    })
</script>
http://我自己的域名/index/index/pushAString?uid=123
ok 为推送成功
offline 为未在线
fail 为失败

프런트엔드 성공 표시 321은 내 맞춤형 UID입니다

메시지 푸시에 Workererman을 사용하는 방법

위 내용은 메시지 푸시에 Workererman을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 csdn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

Nordhold : Fusion System, 설명
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
<exp exp> 모호한 : 원정 33- 완벽한 크로마 촉매를 얻는 방법
2 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구