Constructor __construct
Description:
Worker::__construct([string $listen , array $context])
Initialize a Worker container instance, allowing you to set some properties and callback interfaces of the container to fulfill specific functions.
Parameters
$listen (optional parameter, if not provided, it will not listen to any ports)
If the $listen parameter is set, socket listening will be executed.
The format of $listen is ://
can be one of the following formats:
tcp: for example tcp://0.0.0.0:8686
udp: for example udp://0.0.0.0:8686
unix: for example unix:///tmp/my_file (requires Workerman>=3.2.7)
http: for example http://0.0.0.0:80
websocket: for example websocket://0.0.0.0:8686
text: for example text://0.0.0.0:8686 (text is a built-in text protocol of Workerman, compatible with telnet, details see Appendix Text Protocol section)
And other custom protocols, see the communication protocol customization section of this manual.
can be one of the following formats:
If it is a unix socket, the address is a local disk path.
For non-unix sockets, the address format is :.
can be ```0.0.0.0``` which means listening on all network interfaces of the local machine, including internal IPs, external IPs, and local loopback 127.0.0.1.
If is ```127.0.0.1```, it means listening on the local loopback, accessible only from the local machine, and not from external sources.
If is an internal IP, such as ```192.168.xx.xx```, it means only listening on the internal IP, thus external users cannot access.
If the value set for does not belong to the local IP, it cannot perform listening and will prompt the error ```Cannot assign requested address```.
**Note:** The cannot be greater than 65535. If the is less than 1024, root privileges are required to listen. The listening port must be one that is not occupied on the local machine; otherwise, it cannot listen, and it will prompt the error ```Address already in use```.
#### **``` $context ```**
An array. Used to pass socket context options, see [socket context options](https://php.net/manual/zh/context.socket.php).
## Examples
Worker as an HTTP container listening to handle HTTP requests
```php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('http://0.0.0.0:8686');
$worker->onMessage = function(TcpConnection $connection, Request $request)
{
$connection->send("hello");
};
// Run worker
Worker::runAll();
```
Worker as a WebSocket container listening to handle WebSocket requests
```php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('websocket://0.0.0.0:8686');
$worker->onMessage = function(TcpConnection $connection, $data)
{
$connection->send("hello");
};
// Run worker
Worker::runAll();
```
Worker as a TCP container listening to handle TCP requests
```php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('tcp://0.0.0.0:8686');
$worker->onMessage = function(TcpConnection $connection, $data)
{
$connection->send("hello");
};
// Run worker
Worker::runAll();
```
Worker as a UDP container listening to handle UDP requests
```php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('udp://0.0.0.0:8686');
$worker->onMessage = function(TcpConnection $connection, $data)
{
$connection->send("hello");
};
// Run worker
Worker::runAll();
```
Worker listening on a Unix domain socket ```(requires Workerman version >=3.2.7)```
```php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('unix:///tmp/my.sock');
$worker->onMessage = function(TcpConnection $connection, $data)
{
$connection->send("hello");
};
// Run worker
Worker::runAll();
```
Worker container that does not perform any listening, used to handle some scheduled tasks
```php
use \Workerman\Worker;
use \Workerman\Timer;
require_once __DIR__ . '/vendor/autoload.php';
$task = new Worker();
$task->onWorkerStart = function($task)
{
// Execute once every 2.5 seconds
$time_interval = 2.5;
Timer::add($time_interval, function()
{
echo "task run\n";
});
};
// Run worker
Worker::runAll();
```
**Worker listens to custom protocol ports**
Final directory structure
```
├── Protocols // This is the Protocols directory to be created
│ └── MyTextProtocol.php // This is the custom protocol file to be created
├── test.php // This is the test script to be created
└── Workerman // Workerman source directory, do not modify the code inside
```
1. Create the Protocols directory and create a protocol file
Protocols/MyTextProtocol.php (referring to the above directory structure)
```php
// User-defined protocol namespace is unified as Protocols
namespace Protocols;
// Simple text protocol, protocol format is text + newline
class MyTextProtocol
{
// Fragmentation function, return the length of the current packet
public static function input($recv_buffer)
{
// Look for newline character
$pos = strpos($recv_buffer, "\n");
// If the newline character is not found, it indicates that it is not a complete packet, return 0 to continue waiting for data
if($pos === false)
{
return 0;
}
// If the newline character is found, return the length of the current packet including the newline character
return $pos+1;
}
// After receiving a complete packet, it will automatically decode through decode, here just trim the newline character
public static function decode($recv_buffer)
{
return trim($recv_buffer);
}
// Before sending data to the client, it will automatically encode through encode, then send to the client, here adds a newline
public static function encode($data)
{
return $data."\n";
}
}
```
2. Use MyTextProtocol to listen and handle requests
Create the test.php file according to the final directory structure above
```php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
// #### MyTextProtocol worker ####
$text_worker = new Worker("MyTextProtocol://0.0.0.0:5678");
/*
* After receiving a complete piece of data (ending with a newline), it will automatically execute MyTextProtocol::decode('received data')
* The result is passed to the onMessage callback through $data
*/
$text_worker->onMessage = function(TcpConnection $connection, $data)
{
var_dump($data);
/*
* Sending data to the client will automatically call MyTextProtocol::encode('hello world') for protocol encoding,
* and then send it to the client
*/
$connection->send("hello world");
};
// run all workers
Worker::runAll();
```
3. Testing
Open a terminal, navigate to the directory where test.php is located, and execute ```php test.php start```
```
php test.php start
Workerman[test.php] start in DEBUG mode
----------------------- WORKERMAN -----------------------------
Workerman version:3.2.7 PHP version:5.4.37
------------------------ WORKERS -------------------------------
user worker listen processes status
root none myTextProtocol://0.0.0.0:5678 1 [OK]
----------------------------------------------------------------
Press Ctrl-C to quit. Start success.
```
Open another terminal and test using telnet (recommended to use telnet in a Linux system).
Assuming this is a local test,
execute telnet 127.0.0.1 5678 in the terminal
and then type hi and hit enter,
you will receive data hello world\n
```
telnet 127.0.0.1 5678
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hi
hello world
```