The following is a workerman example test from the workerman tutorial column. I hope it will be helpful to friends in need!
Simple development example
Example 1. Using HTTP protocol to provide external Web services
Create the http_test.php file
<?php use Workerman\Worker; require_once './Workerman/Autoloader.php'; // 创建一个Worker监听2345端口,使用http协议通讯 $http_worker = new Worker("http://0.0.0.0:2345"); // 启动4个进程对外提供服务 $http_worker->count = 4; // 接收到浏览器发送的数据时回复hello world给浏览器 $http_worker->onMessage = function($connection, $data) { // 向浏览器发送hello world $connection->send('hello world'); } ; // 运行worker Worker::runAll();
Run
php http_test.php start
Test
Assume the server ip is 127.0.0.1
Access the url http:/ in the browser /127.0.0.1:2345
Example 2, using WebSocket protocol to provide external services
Create ws_test.php file
<?php use Workerman\Worker; require_once './Workerman/Autoloader.php'; // 创建一个Worker监听2346端口,使用websocket协议通讯 $ws_worker = new Worker("websocket://0.0.0.0:2346"); // 启动4个进程对外提供服务 $ws_worker->count = 4; // 当收到客户端发来的数据后返回hello $data给客户端 $ws_worker->onMessage = function($connection, $data) { // 向客户端发送hello $data $connection->send('hello ' . $data); } ; // 运行worker Worker::runAll();
Run
php ws_test.php start
Test
Open the chrome browser, press F12 to open the debugging console, enter in the Console column (or put the following code into the html page and run it with js)
// 假设服务端ip为127.0.0.1 ws = new WebSocket("ws://127.0.0.1:2346"); ws.onopen = function() { alert("连接成功"); ws.send('tom'); alert("给服务端发送一个字符串:tom"); }; ws.onmessage = function(e) { alert("收到服务端的消息:" + e.data); };
Instance 3, directly use TCP to transmit data
Create tcp_test.php
<?php use Workerman\Worker; require_once './Workerman/Autoloader.php'; // 创建一个Worker监听2347端口,不使用任何应用层协议 $tcp_worker = new Worker("tcp://0.0.0.0:2347"); // 启动4个进程对外提供服务 $tcp_worker->count = 4; // 当客户端发来数据时 $tcp_worker->onMessage = function($connection, $data) { // 向客户端发送hello $data $connection->send('hello ' . $data); } ; // 运行worker Worker::runAll();
Run
php tcp_test.php start
Test
telnet 127.0.0.1 2347Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. tom hello tom
For more workerman knowledge, please Pay attention to the workerman tutorial column.
The above is the detailed content of workerman example test. For more information, please follow other related articles on the PHP Chinese website!