利用Swoole實現PHP+websocket直播,即便通信代碼,及linux下swoole安裝基本配置

php安裝swoole

1. 下載swoole安裝

wget http://pecl.php.net/get/swoole-1.9.1.tgz
tar -zxvf swoole-1.9.1.tgz
cd swoole-1.9.1 phpize ./configure make make install

2. 在php.ini添加swoole.so

extension=swoole.so

php -m查看是否安裝成功

 

環境依賴

  • 僅支持Linux,FreeBSD,MacOS,3類操做系統
  • Linux內核版本2.3.32以上
  • PHP5.3.10以上版本
  • gcc4.4以上版本或者clang
  • cmake2.4+,編譯爲libswoole.so做爲C/C++庫時須要使用cmake 

PHP版本依賴

  • swoole僅支持PHP5.3.10或更高版本,建議使用PHP5.4+
  • swoole不依賴php的stream、sockets、pcntl、posix、sysvmsg等擴展。PHP只需安裝最基本的擴展便可 

PHP直播代碼

1.start.php 使用時須要開啓,服務器輸入(php start.php)javascript

<?php
//php在線直播示例代碼
//使用PHPCLI模式運行
//命令:php start.php

//設置路徑
define('_ROOT_', dirname(__FILE__));
require_once _ROOT_.'/function.php';
//監聽地址和端口
$server = new swoole_websocket_server("0.0.0.0(這裏就是四個0,不要改)", 8888);
//服務端接收鏈接事件
$server->on('open', function (swoole_websocket_server $server, $request) {
    if(!file_exists(_ROOT_.'/client/'.$request->fd.'.client')){
        @file_put_contents(_ROOT_.'/client/'.$request->fd.'.client',$request->fd);
    }
});
//服務端接收信息事件
$server->on('message', function (swoole_websocket_server $server, $frame) {
    foreach(notice(_ROOT_.'/client/') as $v){
            $server->push($v,$frame->data);
    }
});
//服務端接收關閉事件
$server->on('close', function ($ser, $fd) {
    @unlink(_ROOT_.'/client/'.$fd.'.client');
});
//服務開啓
$server->start();

2.index.html 直播頁面,訪問該頁面觀看直播php

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>在線直播界面</title>
</head>
<body>
<img id="receiver" style='width:640px;height:480px'/>
<script type="text/javascript" charset="utf-8">
    var ws = new WebSocket("ws://改爲本身服務器ip:8888");
    var image = document.getElementById('receiver');
    ws.onopen = function(){

    }
    ws.onmessage = function(data)
    {
        image.src=data.data;
    }
</script>
</body>
</html>

3.rec.html主播錄製頁面,訪問該頁面進行直播錄製html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>主播錄製界面</title>
</head>
<body>
<video id="video" autoplay="" style='width:640px;height:480px'></video>
<canvas id="output" style="display:none"></canvas>
<script type="text/javascript" charset="utf-8">
    var ws = new WebSocket("ws://本身服務器ip:8888");
    var back = document.getElementById('output');
    var backcontext = back.getContext('2d');
    var video = document.getElementById("video");
    var success = function(stream){
        video.src = window.URL.createObjectURL(stream);
    }
    ws.onopen = function(){
        draw();
    }
    var draw = function(){
        try{
            backcontext.drawImage(video,0,0, back.width, back.height);
        }catch(e){
            if (e.name == "NS_ERROR_NOT_AVAILABLE") {
                return setTimeout(draw, 100);
            } else {
                throw e;
            }
        }
        if(video.src){
            ws.send(back.toDataURL("image/jpeg", 0.5));
        }
        setTimeout(draw, 100);
    }
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia || navigator.msGetUserMedia;
    navigator.getUserMedia({video:true, audio:false}, success, console.log);
</script>
</body>
</html>

4.function.php 統計數據頁面java

<?php
//統計在線人數
function clearDir($dir)
{
    $n = 0;
    if ($dh = opendir($dir))
    {
        while (($file = readdir($dh)) !== false)
        {
            if ($file == '.' or $file == '..')
            {
                continue;
            }
            if (is_file($dir . $file)) {
                $n++;
            }
        }
    }
    closedir($dh);
    return $n;
}

//通知在線的人
function notice($dir){
    if ($dh = opendir($dir))
    {
        while (($file = readdir($dh)) !== false)
        {
            if ($file == '.' or $file == '..')
            {
                continue;
            }
            if (is_file($dir . $file)) {
                $array[]=file_get_contents($dir.$file);
            }
        }
    }
    closedir($dh);
    return $array;
}

5.在同級目錄下創建client文件,存放信息web

PHP 即便通信

1.socket.php 同樣,使用時須要開啓canvas

<?php
    //建立websocket服務器對象,監聽0.0.0.0:9502端口
    $ws = new swoole_websocket_server("0.0.0.0", 9502);

    //監聽WebSocket鏈接打開事件
    $ws->on('open', function ($ws, $request) {
        $fd[] = $request->fd;
        $GLOBALS['fd'][] = $fd;
        //$ws->push($request->fd, "hello, welcome\n");
    });

    //監聽WebSocket消息事件
    $ws->on('message', function ($ws, $frame) {
        $msg =  'from'.$frame->fd.":{$frame->data}\n";
    //var_dump($GLOBALS['fd']);
    //exit;
        foreach($GLOBALS['fd'] as $aa){
            foreach($aa as $i){
                $ws->push($i,$msg);
            }
        }
       // $ws->push($frame->fd, "server: {$frame->data}");
        // $ws->push($frame->fd, "server: {$frame->data}");
    });

    //監聽WebSocket鏈接關閉事件
    $ws->on('close', function ($ws, $fd) {
        echo "client-{$fd} is closed\n";
    });

    $ws->start();

2.socket.html聊天頁面服務器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="發送數據" onclick="song()">
</body>
<script>
    var msg = document.getElementById("msg");
    var wsServer = 'ws://60.205.208.176:9502';
    //調用websocket對象創建鏈接:
    //參數:ws/wss(加密)://ip:port (字符串)
    var websocket = new WebSocket(wsServer);
    //onopen監聽鏈接打開
    websocket.onopen = function (evt) {
        //websocket.readyState 屬性:
        /*
        CONNECTING    0    The connection is not yet open.
        OPEN    1    The connection is open and ready to communicate.
        CLOSING    2    The connection is in the process of closing.
        CLOSED    3    The connection is closed or couldn't be opened.
        */
        msg.innerHTML = websocket.readyState;
    };

    function song(){
        var text = document.getElementById('text').value;
        document.getElementById('text').value = '';
        //向服務器發送數據
        websocket.send(text);
    }
      //監聽鏈接關閉
//    websocket.onclose = function (evt) {
//        console.log("Disconnected");
//    };

    //onmessage 監聽服務器數據推送
    websocket.onmessage = function (evt) {
        msg.innerHTML += evt.data +'<br>';
//        console.log('Retrieved data from server: ' + evt.data);
    };
//監聽鏈接錯誤信息
//    websocket.onerror = function (evt, e) {
//        console.log('Error occured: ' + evt.data);
//    };

</script>
</html>
相關文章
相關標籤/搜索