zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Github上优秀的.NET Core开源项目的集合
    阿里云服务器CentOS7.5 部署RabbitMQ
    Centos7开放及查看端口
    虚拟机CentOS7.0 部署Redis 5.0.8 集群
    CentOS7 服务检查命令
    CentOS7 常用命令集合
    pyflink小试牛刀
    python mysql pymysql where 当多条件查询,动态出现某些查询条件为空,就不作为条件查询的情况
    centOS6.2 最小安装下的无线网络配置
    Linux命令提示符的配置
  • 原文地址:https://www.cnblogs.com/hoewang/p/10257183.html
Copyright © 2011-2022 走看看