魏魏瑜
魏魏瑜

Reputation: 1

Using WebRTC, unable to implement screen sharing

`The two folders are respectively the client and server. The WebSocket service is monitored under demo.js on the server side using port 8080. The code for both client and server is provided below, and all the printed information seems to be correct, but the screen sharing is not successful. client.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>client</title>
    </head>
    <body>
        <div>
            <h2>客户端</h2>
        </div>
        <video id="remoteVideo" autoplay playsinline controls></video>
        <script src="./client.js"></script>
    </body>
</html>

client.js

const ws = new WebSocket('ws://192.168.110.67:8080');
const pc = new RTCPeerConnection({
    // iceServers: [{
    //  urls: ["stun:stun1.l.google.com:19302", "stun:stun2.l.google.com:19302"]
    // }],
    iceServers: []
});
const remoteStream = new MediaStream();
let localOffer;

pc.ontrack = event => {
    const remoteVideo = document.getElementById('remoteVideo');
    console.log("ontrack", event.streams);
    if (event.streams && event.streams[0]) {
        event.streams[0].getTracks().forEach(track => {
            remoteStream.addTrack(track);
        });
        // console.log('Tracks in the stream:', event.streams[0].getTracks());
        console.log("remoteStream", remoteStream);
        remoteVideo.srcObject = remoteStream;
    } else {
        console.log('Received remote track, but no stream available.');
    }
};

ws.onopen = () => {
    console.log('Connection is open');
};
ws.onmessage = msg => {
    msg.data.text().then(text => {
        console.log('Received message from server:', text);
        if (JSON.parse(text).type === "answer") {
            const answer = JSON.parse(text);
            pc.setRemoteDescription(new RTCSessionDescription(answer)).then(() => {
                console.log("set remotedescription success")
            }).catch(() => {
                console.log("set remotedescription err")
            })
        }
    })

};

pc.createOffer({
    offerToReceiveAudio: 1,
    offerToReceiveVideo: 1
}).then(offer => {
    localOffer = offer;
    return pc.setLocalDescription(localOffer);
}).then(() => {
    sendMessage(JSON.stringify({
        type: 'offer',
        sdp: pc.localDescription.sdp
    }));
});

function sendMessage(message) {
    if (ws.readyState === WebSocket.OPEN) {
        ws.send(message);
    } else {
        console.error('WebSocket is not open: readyState ' + ws.readyState);
    }
}

server.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>server</title>
    </head>
    <body>
        <div>
            <h2>server</h2>
        </div>
        <script src="./server.js"></script>
    </body>
</html>

server.js

const ws = new WebSocket('ws://192.168.110.67:8080');
const pc = new RTCPeerConnection({
    // iceServers: [{
    //  urls: ["stun:stun1.l.google.com:19302", "stun:stun2.l.google.com:19302"]
    // }],
    iceServers: []
});
navigator.mediaDevices.getDisplayMedia({
    video: true,
    audio: true
}).then((stream) => {
    stream.getTracks().forEach(track => pc.addTrack(track, stream))
}).catch(error => {
    console.error('Error sharing the screen:', error);
});
ws.onopen = () => {
    console.log("Connection is open")
}
ws.onmessage = (msg) => {
    msg.data.text().then(text => {
        console.log('Received message from server:', text);
        if (JSON.parse(text).type === "offer") {
            const offer = JSON.parse(text);
            pc.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
                return pc.createAnswer()
            }).then(answer => {
                return pc.setLocalDescription(answer)
            }).then(() => {
                sendMessage(JSON.stringify({
                    type: 'answer',
                    sdp: pc.localDescription.sdp
                }));
            })
        }
    })

}

function sendMessage(message) {
    if (ws.readyState === WebSocket.OPEN) {
        ws.send(message);
    } else {
        console.error('WebSocket is not open: readyState ' + ws.readyState);
    }
}

demo.js

const WebSocket = require('ws');
const wss = new WebSocket.Server({
    port: 8080
});

let clients = [];
let client;
let server;
// 在服务启动并开始监听端口时打印信息
wss.on('listening', () => {
    console.log(`WebSocket server started on port ${wss.options.port}.`);
});

wss.on('connection', function connection(ws) {
    console.log('A new client connected.');
    clients.push(ws);
    server = clients[0];
    if (clients[1]) {
        client = clients[1];
    }
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        const msg = JSON.parse(message);
        if (msg.type === 'offer') {
            server.send(message)
        }
        if (msg.type === 'answer') {
            client.send(message)
        }
    });

    ws.on('close', () => {
        clients = clients.filter(client => client !== ws);
        console.log('Client disconnected.');
    });
});

Although the printed information seems to be without issues, the client is unable to successfully view the shared screen.

Upvotes: 0

Views: 52

Answers (0)

Related Questions