• swoole各种服务器初步搭建


    1.TCP搭建

    <?php
    $host = '192.168.50.66';
    $port = 9501;
    $serv = new swoole_server($host,$port);
    $serv->on('connect',function($serv, $fd){
    	echo "建立连接
    ";
    	var_dump($serv, $fd);
    });
    $serv->on('receive',function($serv, $fd, $reactor_id, $data){
    	echo "收到消息
    ";
    	var_dump($data);
    });
    $serv->on('close',function($serv, $fd){
    	echo "关闭连接
    ";
    	var_dump($serv, $fd);
    });
    $serv->start();

    2.UDP搭建

    <?php
    $serv = new swoole_server("192.168.50.66",11211,SWOOLE_PROCESS,SWOOLE_SOCK_UDP);
    $serv->on('packet',function($serv,$data,$fd){
    	$serv->sendto($fd['address'],$fd['port'],"server:".$data);
    	var_dump($fd);
    });
    $serv->start();

    3.web搭建

    <?php
    $serv = new swoole_http_server("192.168.50.66",9501);
    $serv->on('request',function($request,$response){
    	$response->header("Content-Type","text/html;charset=utf-8");
    	$response->end("hello".rand(100,999));
    });
    $serv->start();

    4.websocket搭建

    <?php
    $ws = new swoole_websocket_server('192.168.50.66',9501);
    $ws->on('open',function($ws,$request){
    	var_dump($request);
    	$ws->push($request->fd,"welcome to hoewang");
    });
    $ws->on('message',function($ws,$request){
    	var_dump($request);
    	$ws->push($request->fd,"you send ".$request->data.'?');
    });
    $ws->on('close',function($ws,$request){
    	echo "close
    ";
    });
    $ws->start();
    客户端代码JS
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Document</title>
    </head>
    <body>
    <script>
    	var wsServer = "ws://192.168.50.66:9501";
    	var webSocket = new WebSocket(wsServer);
    	webSocket.onopen = function(evt){
    		console.log('连接成功');
    	}
    	webSocket.onclose = function(evt){
    		console.log('断开连接');
    	}
    	webSocket.onmessage = function(evt){
    		console.log(evt.data);
    	}
    	webSocket.onerror = function(evt,e){
    		console.log('error');
    	}
    	webSocket->send('hehe');
    </script>
    </body>
    </html>
  • 相关阅读:
    WindowsManager 程序(一) 控制窗口的程序
    SQLServer导入导出资料的方法
    CSS收集(1)
    SQLReporting Service
    WindowsManager 程序(二)
    Microsoft 预发行软件 Visual Studio Team System 2008 测试版 2 Team Suite
    Ajax Pro 使用
    一个获取文件的ICON类
    MyCodeBar我的代码片段管理工具
    ADSL自动断拨号类
  • 原文地址:https://www.cnblogs.com/hoewang/p/10257183.html
Copyright © 2020-2023  润新知