Home  >  Article  >  Backend Development  >  swoole method to create tcp server (code example)

swoole method to create tcp server (code example)

不言
不言forward
2019-01-15 11:41:372771browse

The content of this article is about swoole's method of creating a tcp server (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

server.php

<?php
/**
 * 创建tcp服务器
 * Date: 2019/1/15
 */
$serv = new swoole_server(&#39;127.0.0.1&#39;, 9501);

// 监听连接进入事件
$serv->on(&#39;connect&#39;, function ($serv, $fd) {
    echo "Client: Connect.\n";
});

// 监听数据接收事件
$serv->on(&#39;receive&#39;, function ($serv, $fd, $from_id, $data) {
    $serv->send($fd, "Server: " . $data);
});

// 监听连接关闭事件
$serv->on(&#39;close&#39;, function ($serv, $fd) {
    echo "Client: Close.\n";
});

// 启动服务器
$serv->start();

1. Execute the program and start the server

$  /usr/local/php/bin/

2. After successful startup, check netstat

$ sudo netstat -ntlp | grep php     
tcp        0      0 127.0.0.1:9501          0.0.0.0:*               LISTEN      21314/php

3. Telnet to connect to the server

$ telnet 127.0.0.1 9501Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is &#39;^]&#39;.hello
Server: hello

Exit telnet: shift ], quit

4. End the working process: kill main process ID

$ kill 21314

The above is the detailed content of swoole method to create tcp server (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete