消息推送 HTML5 + swoole websocket server

<?php

namespace app\index\controller;

use swoole_websocket_server;

/*
 * [root@contoso think]# cd /home/myth/www/think && php public/index.php index/Server/run
 * [root@contoso think]# ps -eaf | grep 'index/Server/run' | grep -v 'grep' | awk '{print $2}' | xargs kill -9
 * 
 * [root@contoso ~]# sed -i -- 's/^protected-mode yes/protected-mode no/g' /etc/redis.conf
 * [root@contoso ~]# systemctl restart redis
 * [root@contoso ~]# cat > onlines.sh
  #!/bin/bash
  for ((i = 1;i < 11;i++))
  do
  echo "redis-cli -h 192.168.10.20 -p 6379 sAdd chat:fd:sets $i"
  redis-cli -h 192.168.10.20 -p 6379 sAdd chat:fd:sets $i
  done
 * [root@contoso ~]# bash onlines.sh
 * 
 * [myth@contoso ~]$ ab -r -t 3600 -s 3600 -k -n 1800 -c 200 "http://contoso.org:9502/index/server/run?hi=welcome%20to%20china"
 */

class Server {

    private $redis;
    private $serv;

    public function __construct() {
        ini_set('default_socket_timeout', -1);
    }

    public function run() {
        $this->redis = new \Redis;
        $this->redis->connect('127.0.0.1', 6379, 0);
        $this->serv = new swoole_websocket_server("0.0.0.0", 9502);
        $this->serv->set(array(
            'worker_num' => 4, //worker process num
            'backlog' => 128, //listen backlog
            'max_request' => 50,
            'dispatch_mode' => 1,
        ));

        $this->serv->on('Open', function ($server, $req) {
            $this->redis->sAdd('chat:fd:sets',$req->fd);
            echo "\n connection open: " . $req->fd . "\n";
        });

        $this->serv->on('Message', function ($server, $frame) {
            echo "\n message: " . $frame->data . "\n";
            $onlines = $this->redis->sMembers('chat:fd:sets');
            if (is_array($onlines)) {
                foreach($onlines as $fd){
                    @$server->push($fd, $frame->data);
                }
            }
        });

        // http://contoso.org:9502/index/server/run?hi=moxi,moxi
        $this->serv->on('Request', function ($req, $respone) {
            echo "\n fd: " . $respone->fd . "\n";
            if(isset($req->get['hi'])){  // 判断下是否有数据  
                $onlines = $this->redis->sMembers('chat:fd:sets');
                if(is_array($onlines)){
                    foreach($onlines as $fd){
                        @$this->serv->push($fd, $req->get['hi']);
                    }
                }
            }  
            $respone->end("success");  
        });

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

        $this->serv->start();
    }

}


<!DOCTYPE html>
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>WebSoketClient1</title> 
        <script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
        <script type="text/JavaScript"> 
            //验证浏览器是否支持WebSocket协议
            if (!window.WebSocket) { 
                alert("WebSocket not supported by this browser!"); 
            } 
             var ws;
            function display() { 
                ws=new WebSocket('ws://contoso.org:9502'); 
                //监听消息
                ws.onmessage = function(event) { 
                    log(event.data);
                }; 
                ws.onclose = function(event) { 
                  log("socket连接已断开");
                }; 
                // 打开WebSocket
                ws.onopen = function(){
                    log("socket连接已打开");                    
                };
                ws.onerror =function(event){
                    log("ERROR:" + event.data);
                };
            } 
            var log = function(s) {  
                if (document.readyState !== "complete") {  
                    log.buffer.push(s);  
                } else {  
                    document.getElementById("contentId").innerHTML += (s + "\n");  
                }  
             }  
            function sendMsg(){
                var msg=document.getElementById("messageId");
                ws.send(msg.value); 
            }
        </script> 
    </head> 
    <body οnlοad="display();" width="120px" height="220px"> 
        <textarea rows="20" cols="30" id="contentId"></textarea>
        <br/>
        <input name="message" id="messageId"/>
        <button id="sendButton" onClick="javascript:sendMsg()" >Send</button>
    </body> 
</html> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值