SpringBoot+WebSocket+WebRTC を使用してビデオ通話を実装する方法を学ぶ 1 時間

SpringBoot+WebSocket+WebRTC を使用してビデオ通話を実装する方法を学ぶ 1 時間

1. 走行結果

SpringBoot+WebSocket+WebRTCでビデオ通話を実現

上記の実行結果には、音声 (比較的小さい) と動画 (静止画ではありません) が含まれています。

webrtc に関するドキュメント(記事)や動画はインターネット上にたくさんありますが、SpringBoot を使って WebRTC を組み合わせている人はほんの一握りです。少し前に WebRTC について知り、SpringBoot+WebRTC を使用して実装しました複数人 オンライン自習室 (画像はありますが音声はありません。音声をオンにするのは非常に簡単です。js コードで設定するだけです (実行結果は最終概要にあります))。最近、CSDN で、少し前に学んだ知識を適用するアクティビティがあります (次のコードは実装されているだけですが、ロジックに特定の問題があるため、読者が次のコードを使用する場合は、忘れずに変更してください)。WebRTCなのになぜまたWebSocketと関係するのか?WebSocket テクノロジを使用してメッセージを送信するのはリアルタイムであるため、こちら側でメッセージを送信しますが、相手側が接続されている限り、メッセージを受信できます。また、http、https などを使用する場合は、こちら側でメッセージを送信し、相手側でメッセージを確認するにはページを更新する必要があります (もちろん、タイマーを設定できます)。WebSocket技術と組み合わせることで、ビデオ通話機能を高速に実現できます。

2. 実現する

次のように、関連する jar パッケージの依存関係をインポートします。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.10</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

上記には不要な jar パッケージがいくつかある可能性があります。

2.1 バックエンドの実装

WebSocket 構成クラス
GetHttpSessionConfig.class

package com.example.demo.websocket2;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {
    
    

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    
    

        HttpSession httpSession = (HttpSession) request.getHttpSession();

        // 获取httpsession对象

        sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
    }
}

Config.class での ServerEndpointExporter Bean の定義

package com.example.demo.websocket2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class Config {
    
    

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
    
    

        return new ServerEndpointExporter();
    }
}

*ウェブソケットサーバークラス WebSocketServer*

package com.example.demo.websocket2;

import org.springframework.stereotype.Component;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/video",configurator = GetHttpSessionConfig.class)
public class WebSocketServer {
    
    

    //存储客户端的连接对象,每个客户端连接都会产生一个连接对象
    private static ConcurrentHashMap<String,WebSocketServer> map = new ConcurrentHashMap();
    //每个连接都会有自己的会话
    private Session session;
    private String account;

    @OnOpen
    public void open(Session session,EndpointConfig config){
    
    

        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String account = String.valueOf(httpSession.getAttribute("account"));

        map.put(account,this);

        this.session = session;
        this.account = account;
    }

    @OnClose
    public void close(){
    
    
        map.remove(account);
    }

    @OnError
    public void error(Throwable error){
    
    
        error.printStackTrace();
    }

    @OnMessage
    public void getMessage(String message) throws IOException {
    
    

        Set<Map.Entry<String, WebSocketServer>> entries = map.entrySet();
        for (Map.Entry<String, WebSocketServer> entry : entries) {
    
    
            if(!entry.getKey().equals(account)){
    
    //将消息转发到其他非自身客户端
                entry.getValue().send(message);
            }
        }
    }

    public void send(String message) throws IOException {
    
    
        if(session.isOpen()){
    
    
            session.getBasicRemote().sendText(message);
        }
    }

    public int  getConnetNum(){
    
    
        return map.size();
    }
}

2.2 フロントエンドページの実現

ログイン インターフェースのコードはここには貼り付けません。以下は主にビデオ通話インターフェースのコード (CSS スタイルと JS コードを含む) を示しています。

<html>

<head>
    <title>main</title>
    <link rel = "stylesheet" href = "https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap-theme.min.css"/>

</head>

<style>

    body {
      
      
        background: #eee;
        padding: 5% 0;
    }

    video {
      
      
        background: black;
        border: 1px solid gray;
    }

    .call-page {
      
      
        position: relative;
        display: block;
        margin: 0 auto;
        width: 500px;
        height: 500px;
    }

    #localVideo {
      
      
        width: 150px;
        height: 150px;
        position: absolute;
        top: 15px;
        right: 15px;
    }

    #remoteVideo {
      
      
        width: 500px;
        height: 500px;
    }

</style>

<body>

<div id = "callPage" class = "call-page">
    <video id = "localVideo" autoplay></video>
    <video id = "remoteVideo" autoplay></video>

    <div class = "row text-center">
        <div class = "col-md-12">
            <input id = "callToUsernameInput" type = "text"
                   placeholder = "username to call" />
            <button id = "callBtn" class = "btn-success btn">Call</button>
            <button id = "hangUpBtn" class = "btn-danger btn">Hang Up</button>
        </div>
    </div>

</div>

<script type="text/javascript">
    //our username
    var connectedUser;

    //connecting to our signaling server
    var conn = new WebSocket("ws://localhost:9999/video");

    conn.onopen = function () {
      
      
        console.log("Connected to the signaling server");
    };

    //when we got a message from a signaling server
    conn.onmessage = function (msg) {
      
      
        console.log("Got message", msg.data);

        var data = JSON.parse(msg.data);

        switch(data.type) {
      
      
            case "login":
                handleLogin(data.success);
                break;
            //when somebody wants to call us
            case "offer":
                handleOffer(data.offer, data.name);
                break;
            case "answer":
                handleAnswer(data.answer);
                break;
            //when a remote peer sends an ice candidate to us
            case "candidate":
                handleCandidate(data.candidate);
                break;
            case "leave":
                handleLeave();
                break;
            default:
                break;
        }
    };

    conn.onerror = function (err) {
      
      
        console.log("Got error", err);
    };

    //alias for sending JSON encoded messages
    function send(message) {
      
      
        //attach the other peer username to our messages
        if (connectedUser) {
      
      
            message.name = connectedUser;
        }

        conn.send(JSON.stringify(message));
    }

    //******
    //UI selectors block
    //******


    var callPage = document.querySelector("#callPage");
    var callToUsernameInput = document.querySelector("#callToUsernameInput");
    var callBtn = document.querySelector("#callBtn");

    var hangUpBtn = document.querySelector("#hangUpBtn");

    var localVideo = document.querySelector("#localVideo");
    var remoteVideo = document.querySelector("#remoteVideo");

    var yourConn;
    var stream;

    // callPage.style.display = "none";

    var PeerConnection = (window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.RTCPeerConnection || undefined);
    var RTCSessionDescription = (window.webkitRTCSessionDescription || window.mozRTCSessionDescription || window.RTCSessionDescription || undefined);

    navigator.getUserMedia = (navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia);
    //**********************
    //Starting a peer connection
    //**********************

    //getting local video stream
    navigator.getUserMedia({
      
       video: true, audio: true }, function (myStream) {
      
      
        stream = myStream;

        //displaying local video stream on the page
        localVideo.srcObject = stream;

        //using Google public stun server
        var configuration = {
      
      
            "iceServers": []
        };

        yourConn = new PeerConnection(configuration);

        // setup stream listening
        yourConn.addStream(stream);

        //when a remote user adds stream to the peer connection, we display it
        yourConn.onaddstream = function (e) {
      
      
            remoteVideo.srcObject = e.stream;
        };

        // Setup ice handling
        yourConn.onicecandidate = function (event) {
      
      
            if (event.candidate) {
      
      
                send({
      
      
                    type: "candidate",
                    candidate: event.candidate
                });
            }
        };

    }, function (error) {
      
      
        console.log(error);
    });


    //initiating a call
    callBtn.addEventListener("click", function () {
      
      
        var callToUsername = callToUsernameInput.value;

        if (callToUsername.length > 0) {
      
      

            connectedUser = callToUsername;

            // create an offer
            yourConn.createOffer(function (offer) {
      
      
                send({
      
      
                    type: "offer",
                    offer: offer
                });

                yourConn.setLocalDescription(offer);
            }, function (error) {
      
      
                alert("Error when creating an offer");
            });

        }
    });

    //when somebody sends us an offer
    function handleOffer(offer, name) {
      
      
        connectedUser = name;
        yourConn.setRemoteDescription(new RTCSessionDescription(offer));

        //create an answer to an offer
        yourConn.createAnswer(function (answer) {
      
      
            yourConn.setLocalDescription(answer);

            send({
      
      
                type: "answer",
                answer: answer
            });

        }, function (error) {
      
      
            alert("Error when creating an answer");
        });
    }

    //when we got an answer from a remote user
    function handleAnswer(answer) {
      
      
        yourConn.setRemoteDescription(new RTCSessionDescription(answer));
    }

    //when we got an ice candidate from a remote user
    function handleCandidate(candidate) {
      
      
        yourConn.addIceCandidate(new RTCIceCandidate(candidate));
    }

    //hang up
    hangUpBtn.addEventListener("click", function () {
      
      

        send({
      
      
            type: "leave"
        });

        handleLeave();
    });

    function handleLeave() {
      
      
        connectedUser = null;
        remoteVideo.src = null;

        yourConn.close();
        yourConn.onicecandidate = null;
        yourConn.onaddstream = null;
    }
</script>

</body>

</html>

3. まとめ

上記のフロントエンド コードのリファレンスは、webrtc ビデオ デモから取得しています。上記のコードを理解していない読者がいる場合は、webrtc の詳細な紹介と実装が記載されているこのリンクで知識を詳しく見ることができます。複数人での話ではなく、1対1の話でしたが、少し前に編集者も偉い人の実装案を参考に自分なりに考えて複数人での話も実現しました。 . 実行結果は以下の通りです。

SpringBoot、WebSocket、WebRTCをベースに多人数自習室の機能を実現

おすすめ

転載: blog.csdn.net/qq_45404396/article/details/131348216