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

字號+ 編輯: 国内TP粉 修訂: 种花家 來源: cnblogs 2023-10-02 我要說兩句(0)

一篇具有參考價值的文章, 饗給各位開發大神。

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或者php --ri swoole查看插件列表裡是否有swoole, 有的話代表安裝成功

環境依賴

僅支持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)


<?php

// 使用PHPCLI模式運行

// 設置路徑
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 直播頁面,訪問該頁面觀看直播

<!DOCTYPE html>
<html>
<head>
    <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主播錄制頁面,訪問該頁面進行直播錄制

<!DOCTYPE html>
<html>
<head>
    <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 統計數據頁面

<?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文档,存放信息

PHP 即時通訊

1.socket.php 一樣,使用時需要開啓

<?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>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="發送數據" ="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);
    }
      // 監聽連接關閉

//        console.log("Disconnected");

    // onmessage 監聽服務器數據推送
    websocket.onmessage = function (evt) {
        msg.innerHTML += evt.data +'<br>';

    };

//    websocket.onerror = function (evt, e) {

//    };
</script>
</html>


閲完此文,您的感想如何?
  • 有用

    0

  • 沒用

    1

  • 開心

    0

  • 憤怒

    0

  • 可憐

    0

1.如文章侵犯了您的版權,請發郵件通知本站,該文章將在24小時内刪除;
2.本站標注原創的文章,轉發時煩請注明來源;
3.交流群: 2702237 13835667

相關課文
  • mac開發接入微信公衆號接口返回報錯 cURL error 56: SSLRead() return error -9806

  • PHP的換行符是什麽

  • pecl安裝程序時報錯Array and string offset access syntax with curly braces is no longer supported

  • 由於商家傳入的H5交易參數有誤,該筆交易暫時無法完成,請聯繫商家解決

我要說說
網上賓友點評