Home > PHP Framework > Workerman > body text

How to download workerman

(*-*)浩
Release: 2019-12-02 09:31:27
Original
3483 people have browsed it

How to download workerman

First download workerman https://www.workerman.net/download (Recommended learning: workerman tutorial)

How to download workerman

After downloading, create a new file start.php under the workerman file

How to download workerman

##The code is as follows

<?php
use Workerman\Worker;
 
//Autoloader.php路径
require_once "./Autoloader.php";
 
$global_uid = 0;
 
// 当客户端连上来时分配uid,并保存连接,并通知所有客户端
function handle_connection($connection)
{
    global $text_worker, $global_uid;
    // 为这个连接分配一个uid
    $connection->uid = ++$global_uid;
}
 
// 当客户端发送消息过来时,转发给所有人
function handle_message($connection, $data)
{
    global $text_worker;
    foreach($text_worker->connections as $conn)
    {
        $conn->send("user[{$connection->uid}] said: $data");
    }
}
 
// 当客户端断开时,广播给所有客户端
function handle_close($connection)
{
    global $text_worker;
    foreach($text_worker->connections as $conn)
    {
        $conn->send("user[{$connection->uid}] logout");
    }
}
 
// 创建一个文本协议的Worker监听2000接口  用0.0.0.0方便链接内网外网
$text_worker = new Worker("websocket://0.0.0.0:2000");  
 
// 只启动1个进程,这样方便客户端之间传输数据
$text_worker->count = 1;
 
$text_worker->onConnect = &#39;handle_connection&#39;;
$text_worker->onMessage = &#39;handle_message&#39;;
$text_worker->onClose = &#39;handle_close&#39;;
 
Worker::runAll();
Copy after login

Then run the command line php start.php start

Simple test is to open the browser and press F12 to open it Debug the console, enter in the Console column (or put the following code into the html page and run it with jsHow to download workerman

// 假设服务端ip为127.0.0.1
ws = new WebSocket("ws://127.0.0.1:2000");
ws.onopen = function() {
    alert("连接成功");
    ws.send(&#39;我是谁?&#39;);
    alert("给服务端发送一个字符串:我是谁?");
};
ws.onmessage = function(e) {
    alert("收到服务端的消息:" + e.data);
};
Copy after login

How to download workerman

The above is the detailed content of How to download workerman. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!