Use PHP's swoole framework to achieve high-performance long connections Websocket__web

Source: Internet
Author: User

Swoole's official website please see: http://www.swoole.com/
SWOOLE-GIT:HTTPS://GITHUB.COM/SWOOLE/SWOOLE-SRC one. Server side: 1. The contents of the edit server.php file are as follows:

<?php
$reqs =array ();//Keep the client's long connection in this array
$serv = new Swoole_websocket_server ("192.168.2.115", 9502);
The following can be set up multiport listening
//$server = new Swoole_websocket_server ("0.0.0.0", 9501, swoole_base);
$server->addlistener (' 0.0.0.0 ', 9502, swoole_sock_udp);
$server->set ([' Worker_num ' => 4]);

$serv->on (' Open ', function ($server, $req) {
    global $reqs;
    $reqs []= $req->fd;
    echo "Connection open:". $req->fd. " \ n ";
    Var_dump (Count ($reqs));//Output Long connections
});

$serv->on (' message ', function ($server, $frame) {
    global $reqs;
    echo "message:" $frame->data. " \ n ";
    foreach ($reqs as $FD) {
            $server->push ($FD, $frame->data);
    }
);

$serv->on (' Close ', function ($server, $FD) {
    echo "connection close:". $fd. " \ n ";
});

$serv->start ();
2. Start the WebSocket service code implemented above
[Songaimin@localhost tests]$/usr/bin/php server.php
Client-Colleague opens two browsers to simulate multiple client: 3. Run in Browser console:
var wsl= ' ws://192.168.2.115:9502 '
ws = new WebSocket (WSL);//Newly set up a connection
//The following specified event handling 
Ws.onopen = function () { Ws.send (' test! '); };  
Ws.onmessage = function (evt) {console.log (evt.data);/*ws.close ()  
; Ws.onclose = function (evt) {console.log (' websocketclosed! ');  
4. Manually execute in any browser console:
Ws.send (888);
Look at the contents of each browser the console output should be the same on the experiment on the success of the
Ws.close ();/close Connection

Related Recommended articles:
Real-time chat room http://segmentfault.com/a/1190000003057118 implemented by Swoole

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.