1. 程式人生 > >建立tcp伺服器

建立tcp伺服器

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/3
 * Time: 16:00
 */
//建立伺服器 TCP伺服器
$serv = new swoole_server('192.168.1.234', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
//監聽連線進入事件
$serv->on('connect', function ($serv, $fd) {
foreach($serv->connections as $fd)
    {
$serv->send(
$fd, "當前伺服器共有 ".count($serv->connections). " 個連線\n"); } echo "當前伺服器共有 ".count($serv->connections). " 個連線\n"; }); //監聽資料傳送事件 $serv->on('receive', function ($serv, $fd, $from_id, $data) { print_r($from_id); $serv->send($fd, "伺服器---Server: ".$data); }); //監聽連線關閉事件 $serv->on('close', function
($serv, $fd) { print_r($serv); foreach($serv->connections as $fd) { $serv->send($fd,"當前伺服器共有 ".(count($serv->connections)-1). " 個連線\n"); } echo "當前伺服器共有 ".(count($serv->connections)-1). " 個連線\n"; }); //啟動伺服器 $serv->start();