´Ó»ù´¡µ½Êµ¼ù£¬ÊÖ°ÑÊÖ½ÌÄãѧϰSwoole
Ëæ×Å»¥ÁªÍøʱ´úµÄÒ»Ö±Éú³¤ºÍÇ°½ø£¬webÓ¦ÓóÌÐòµÄÐÔÄÜÒѳÉΪÆóÒµÉú³¤µÄÒªº¦Ö®Ò»¡£È»¶ø£¬¹Å°åµÄphpÔڸ߲¢·¢¡¢´óÁ÷Á¿µÄÇéÐÎϾ³£ÈÝÒ×Í߽⣬ӰÏìÓ¦ÓóÌÐòµÄÐÔÄܺÍÓû§ÌåÑ顣ΪÏàʶ¾öÕâ¸öÎÊÌ⣬swooleÓ¦Ô˶øÉú¡£
SwooleÊÇÒ»¿î¸ßÐÔÄܵÄPHPг̿ò¼Ü£¬¿ÉÒÔʵÏָ߲¢·¢¡¢Òì²½±à³Ì£¬´ó´óÌáÉýWebÓ¦ÓóÌÐòµÄÐÔÄܺÍЧÂÊ¡£±¾ÎĽ«ÊÖ°ÑÊÖ½ÌÄã´Ó»ù´¡µ½Êµ¼ùѧϰSwoole¡£
Ò»¡¢SwooleµÄ»ù´¡ÖªÊ¶
г̿´·¨
гÌÊÇÒ»ÖÖÓû§Ì¬µÄÇáÁ¿¼¶Ị̈߳¬²î±ðÓÚ²Ù×÷ϵͳµÄÏ̡߳£ËüÖ»ÐèÒªÇл»ÉÏÏÂÎĶø²»ÐèÒª¾ÙÐÐϵͳŲÓã¬Çл»µÄËÙÂʽÏÁ¿¿ì£¬Õ¼ÓÃÄÚ´æÒ²½ÏÁ¿Ð¡¡£Ð³Ì¿ÉÒÔ´ó´óÌá¸ß³ÌÐòµÄ²¢·¢ÐÔÄÜ¡£
SwooleµÄÌصã
¸ß²¢·¢¡¢¸ßÐÔÄÜ¡£
Ö§³ÖÒì²½IO²Ù×÷¡£
ÌṩÁËÍêÉƵÄÍøÂçͨѶÐÒ飬ÈçHTTP¡¢WebSocket¡¢TCP¡¢UDPµÈ¡£
Ö§³Öг̣¬¿ÉÒÔʵÏÖÒì²½±à³Ì¡£
ÌṩÁ˶àÀú³Ì¡¢¶àÏß³ÌÄ£×Ó£¬¿ÉÒÔ³ä·ÖʹÓöàºËCPU¡£
¶þ¡¢SwooleµÄ×°ÖÃ
ÇéÐÎÒªÇó
PHP°æ±¾´óÓÚ7.0¡£
Linux¡¢Unix»òMacOS²Ù×÷ϵͳ¡£
×°ÖÃÏÂÁî
ÔÚÏÂÁîÐÐÖÐÖ´ÐÐÒÔÏÂÏÂÁî¼´¿É×°ÖÃSwooleÀ©Õ¹£º
pecl install swoole
µÇ¼ºó¸´ÖÆ
×°ÖÃÍê³Éºó£¬ÔÚphp.iniÎļþÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
extension=swoole.so
µÇ¼ºó¸´ÖÆ
ÉúÑIJ¢ÖØÆôPHP-FPM¡£
Èý¡¢SwooleµÄʹÓÃ
¼òÆÓ°¸Àý
ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄSwoole°¸Àý£¬¿ÉÒÔÊä³öHello, Swoole!£º
<?php $http = new swoole_http_server("127.0.0.1", 9501); $http->on("start", function ($server) { echo "Swoole http server is started at http://127.0.0.1:9501 "; }); $http->on("request", function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello, Swoole!"); }); $http->start();
µÇ¼ºó¸´ÖÆ
ÔÚÏÂÁîÐÐÖÐÖ´ÐÐphp ÎļþÃûÏÂÁ·¿ªä¯ÀÀÆ÷»á¼û http://localhost:9501£¬¾Í¿ÉÒÔ¿´µ½Êä³öÁËHello, Swoole! ¡£
WebSocket°¸Àý
ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄSwoole WebSocket°¸Àý£¬¿ÉÒÔʵÏÖ¼òÆÓµÄ̸ÌìÊÒ¹¦Ð§£º
<?php $serv = new swoole_websocket_server("127.0.0.1", 9502); $serv->on('open', function ($server, $req) { echo "connection open: {$req->fd} "; }); $serv->on('message', function ($server, $frame) { echo "received message: {$frame->data} "; $server->push($frame->fd, json_encode(["hello", "world"])); }); $serv->on('close', function ($server, $fd) { echo "connection close: {$fd} "; }); $serv->start();
µÇ¼ºó¸´ÖÆ
ÔÚÏÂÁîÐÐÖÐÖ´ÐÐphp ÎļþÃûÏÂÁ·¿ªä¯ÀÀÆ÷¿ØÖÆ̨£¬Ö´ÐÐÒÔÏÂJS´úÂ룺
var ws = new WebSocket('ws://127.0.0.1:9502'); ws.onopen = function() { console.log('WebSocket is connected'); }; ws.onmessage = function (evt) { console.log('received message: ' + evt.data); }; ws.onclose = function() { console.log('WebSocket is closed'); }; ws.send('Hello Swoole WebSocket');
µÇ¼ºó¸´ÖÆ
ÔËÐк󣬾ͿÉÒÔ¿´µ½¿ØÖÆ̨Êä³öÁËWebSocket is connectedºÍreceived message: [“hello”,”world”]¡£
ËÄ¡¢×ܽá
ͨ¹ý±¾ÎĵÄÏÈÈÝ£¬ÐÅÍи÷ÈËÒѾÕÆÎÕÁËSwooleг̿ò¼ÜµÄ»ù±¾ÖªÊ¶ºÍʹÓÃÒªÁì¡£ÔÚÏÖʵ¿ª·¢ÖУ¬ÎÒÃÇ¿ÉÒÔ³ä·ÖʹÓÃSwooleµÄ¸ß²¢·¢¡¢¸ßÐÔÄܺÍÒì²½±à³ÌµÈÌص㣬À´ÌáÉýWebÓ¦ÓóÌÐòµÄÐÔÄܺÍЧÂÊ¡£
ÒÔÉϾÍÊÇ´Ó»ù´¡µ½Êµ¼ù£¬ÊÖ°ÑÊÖ½ÌÄãѧϰSwooleµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡