백엔드 개발 PHP 튜토리얼 라이브 비디오 및 오디오 채팅을 위해 PHP에서 WebSockets API를 사용하는 방법

라이브 비디오 및 오디오 채팅을 위해 PHP에서 WebSockets API를 사용하는 방법

Jun 17, 2023 pm 02:37 PM
php websockets 실시간 상호작용

WebSockets API는 실시간 영상 및 음성 채팅을 구현하는 데 중요한 부분으로, 양방향 통신을 실현할 수 있는 이벤트 기반 메커니즘을 기반으로 하는 통신 방법을 제공하여 브라우저와 서버 간의 통신을 더욱 간단하고 빠르며 안전하게 만듭니다. . 이 기사에서는 실시간 비디오 및 오디오 채팅을 위해 PHP에서 WebSockets API를 사용하는 방법을 소개합니다.

  1. WebSocket 서버 설치

PHP에서 WebSockets API를 사용하려면 먼저 WebSocket 서버를 설치해야 합니다. PHP에서 가장 널리 사용되는 WebSocket 서버인 Rachet을 사용하는 것이 좋습니다. Composer를 사용하여 설치할 수 있습니다:

composer require cboden/ratchet
로그인 후 복사
  1. WebSocket 서버 생성

Rachet을 사용하여 WebSocket 서버를 생성하는 것은 매우 간단하며 몇 줄의 코드만 필요합니다.

require dirname(__DIR__) . '/vendor/autoload.php';

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})
";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        broadcast($msg);
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected
";
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "An error has occurred: {$e->getMessage()}
";
        $conn->close();
    }

    public function broadcast($msg) {
        foreach ($this->clients as $client) {
            $client->send($msg);
        }
    }
}

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);

echo "Server started!
";

$server->run();
로그인 후 복사

이 서버는 모든 연결을 수락하고 도착하는 메시지를 브로드캐스트합니다. . Grad 스트림 객체를 사용하여 모든 연결을 저장합니다.

  1. 프런트 엔드 애플리케이션 만들기

WebSockets API를 사용하면 크로스 플랫폼과 크로스 브라우저에서 프런트 엔드 애플리케이션을 만들 수 있습니다. JavaScript를 사용하여 프런트 엔드 애플리케이션을 만드는 방법은 다음과 같습니다.

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">

    <title>Chat</title>
    <meta name="description" content="Chat">
    <meta name="author" content="Chat">

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>

    <style>
        #log {
            height: 200px;
            overflow: auto;
        }
    </style>
</head>

<body>
    <div id="log"></div>
    <input type="text" id="message">
    <button id="send">Send</button>
    <script>
        var socket = io('http://localhost:8080');

        socket.on('message', function (data) {
            $('#log').append('<p>' + data + '</p>');
        });

        $('#send').click(function() {
            var message = $('#message').val();
            socket.emit('message', message);
        });
    </script>
</body>
</html>
로그인 후 복사

Socket.io를 사용하여 연결하면 애플리케이션이 메시지를 받고 보냅니다.

  1. 영상 및 음성 채팅 구현

Ratchet 및 WebSockets API를 통해 양방향 실시간 영상 및 음성 채팅이 가능하며, 이를 위해서는 몇 가지 추가 라이브러리와 도구를 사용해야 합니다. 브라우저 간 P2P 통신을 허용하는 실시간 통신의 최신 표준인 WebRTC를 사용하는 것이 좋습니다.

PHP에서 WebSocket 서버와 WebRTC DSP를 사용하면 양방향 실시간 비디오 및 오디오 채팅 애플리케이션을 만들 수 있습니다. 이를 위해서는 몇 가지 추가 JavaScript 코드가 필요하며 SimpleWebRTC를 사용하여 구현할 수 있습니다.

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">

    <title>Chat</title>
    <meta name="description" content="Chat">
    <meta name="author" content="Chat">

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>
    <script src="//simplewebrtc.com/latest-v3.js"></script>

    <style>
        #log {
            height: 200px;
            overflow: auto;
        }

        #localVideo {
            width: 200px;
            height: 150px;
            margin-bottom: 10px;
        }

        #remoteVideos video {
            width: 400px;
            height: 300px;
            margin-bottom: 10px;
        }
    </style>
</head>

<body>
    <div id="log"></div>
    <div id="localVideo"></div>
    <div id="remoteVideos"></div>
    <script>
        var server = {
            url: 'http://localhost:8080',
            options: {},
            // Use media servers for production
            signalingServerUrl: 'https://localhost:8888'
        };

        var webrtc = new SimpleWebRTC({
            localVideoEl: 'localVideo',
            remoteVideosEl: 'remoteVideos',
            autoRequestMedia: true,
            url: server.url,
            socketio: {'force new connection': true},
            debug: false,
            detectSpeakingEvents: true,
            autoAdjustMic: false,
            peerConnectionConfig: {
                iceServers: [
                    {url: 'stun:stun.l.google.com:19302'},
                    {url:'stun:stun1.l.google.com:19302'},
                    {url:'stun:stun2.l.google.com:19302'}
                ]
            },
            receiveMedia: {
                mandatory: {
                    OfferToReceiveAudio: true,
                    OfferToReceiveVideo: true
                }
            }
        });

        webrtc.on('readyToCall', function () {
            console.log('readyToCall');
            webrtc.joinRoom('chat');
        });

        webrtc.on('localStream', function (stream) {
            console.log('localStream');
            $('#localVideo').show();
        });

        webrtc.on('videoAdded', function (video, peer) {
            console.log('videoAdded');
            $('#remoteVideos').append('<video id="' + peer.id + '" autoplay></video>');
            webrtc.attachMediaStream($('#' + peer.id), video);
        });

        webrtc.on('videoRemoved', function (video, peer) {
            console.log('videoRemoved');
            $('#' + peer.id).remove();
        });

        webrtc.on('channelMessage', function (peer, label, message) {
            console.log('channelMessage');
            console.log('peer: ' + peer);
            console.log('label: ' + label);
            console.log('message: ' + message);
        });
    </script>
</body>
</html>
로그인 후 복사

SimpleWebRTC는 여기에서 비디오 및 오디오 채팅을 구현하는 데 사용됩니다. 코드에는 클라이언트 및 서버 코드가 포함되어 있으며, 사용자가 페이지를 방문하면 클라이언트는 WebSocket 서버에 연결하고 룸에 참여하려고 시도합니다. 서버는 WebSocket 이벤트를 SimpleWebRTC에 전달합니다.

요약

Rachet 및 WebSockets API를 사용하면 양방향 실시간 영상 및 음성 채팅이 가능합니다. SimpleWebRTC를 사용하면 실시간 오디오 및 비디오 채팅을 지원하도록 애플리케이션을 쉽게 확장할 수 있습니다. WebRTC는 온라인 교육 시스템, 협업 애플리케이션, 온라인 게임 등 다양한 애플리케이션에서 사용할 수 있는 강력한 기술입니다. PHP에서 WebSockets API와 WebRTC를 사용하면 강력한 실시간 애플리케이션을 만들 수 있습니다.

위 내용은 라이브 비디오 및 오디오 채팅을 위해 PHP에서 WebSockets API를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP 데이터베이스 작업 CakePHP 데이터베이스 작업 Sep 10, 2024 pm 05:25 PM

CakePHP에서 데이터베이스 작업은 매우 쉽습니다. 이번 장에서는 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 이해하겠습니다.

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

cakephp4에서 날짜와 시간을 다루기 위해 사용 가능한 FrozenTime 클래스를 활용하겠습니다.

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

파일 업로드 작업을 위해 양식 도우미를 사용할 것입니다. 다음은 파일 업로드의 예입니다.

CakePHP 라우팅 CakePHP 라우팅 Sep 10, 2024 pm 05:25 PM

이번 장에서는 라우팅과 관련된 다음과 같은 주제를 학습하겠습니다.

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

CakePHP 유효성 검사기 만들기 CakePHP 유효성 검사기 만들기 Sep 10, 2024 pm 05:26 PM

컨트롤러에 다음 두 줄을 추가하면 유효성 검사기를 만들 수 있습니다.

CakePHP 로깅 CakePHP 로깅 Sep 10, 2024 pm 05:26 PM

CakePHP에 로그인하는 것은 매우 쉬운 작업입니다. 한 가지 기능만 사용하면 됩니다. cronjob과 같은 백그라운드 프로세스에 대해 오류, 예외, 사용자 활동, 사용자가 취한 조치를 기록할 수 있습니다. CakePHP에 데이터를 기록하는 것은 쉽습니다. log() 함수는 다음과 같습니다.

See all articles