WebRTC соединение на локальном хосте без подключения к интернету - PullRequest
2 голосов
/ 13 июня 2019

Я пытаюсь создать RTCPeerConnection между камерой-сервисом, написанным на Python с aiortc, и веб-интерфейсом в javascript без подключения к интернету.

Camera-сервис осуществляет доступ к usb-камере и предоставляет поток для двух других сервисов.Для внешнего интерфейса, написанного на javascript и сервиса классификации изображений, написанного на python.Все эти службы работают на разных портах на локальном хосте.Мне нужно сделать это без подключения к интернету.

RTCPeerConnection между двумя сервисами python работает без подключения к Интернету, но не работает соединение между внешним интерфейсом и сервисом камеры.

Без подключения к Интернету ICEConnectionState камеры-сервиса никогда не завершает только проверку, поэтому я думаю, что здесь есть какая-то проблема.

Чтобы воспроизвести эту проблему, просто попробуйте пример веб-камеры aiortc (https://github.com/aiortc/aiortc/tree/master/examples/webcam) с подключением к Интернету и без него.

front-end в javascript


var pc = new RTCPeerConnection({
    "iceServers": []
});

//start the negotiating process with camera-service(running on localhost:8080)
function negotiate() {
    pc.addTransceiver('video', {direction: 'recvonly'});
    return pc.createOffer().then(function(offer) {
        return pc.setLocalDescription(offer);
    }).then(function() {
        // wait for ICE gathering to complete
        return new Promise(function(resolve) {
            if (pc.iceGatheringState === 'complete') {
                resolve();
            } else {
                function checkState() {
                    if (pc.iceGatheringState === 'complete') {
                        pc.removeEventListener('icegatheringstatechange', checkState);
                        resolve();
                    }
                }
                pc.addEventListener('icegatheringstatechange', checkState);
            }
        });
    }).then(function() {
        var offer = pc.localDescription;
        const url = 'http://localhost:8080/offer';
        return fetch(url, {
        body: JSON.stringify({
            sdp: offer.sdp,
                type: offer.type,
            }),
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST'
        });
    }).then(function(response) {
        return response.json();
    }).then(function(answer) {
        return pc.setRemoteDescription(answer);
    }).catch(function(e) {
        alert(e);
    });
}

служба камеры в Python

# method gets called on POST request to localhost:8080/offer
async def offer(request):

    params = await request.json()
    offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])

    pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
    pcs.add(pc)

    @pc.on("iceconnectionstatechange")
    async def on_iceconnectionstatechange():
        print("ICE connection state is %s" % pc.iceConnectionState)
        if pc.iceConnectionState == "failed":
            await pc.close()
            pcs.discard(pc)

    pc.addTrack(player.video)

    await pc.setRemoteDescription(offer)

    answer = await pc.createAnswer()
    await pc.setLocalDescription(answer)

    response = web.Response(
        content_type="application/json",
        body=json.dumps({
            "sdp": pc.localDescription.sdp,
            "type": pc.localDescription.type}))

    return response

служба классификации изображений в Python

async def negotiate(request):
    pc = RTCPeerConnection()
    pcs.add(pc)

    pc.addTransceiver('video',direction='recvonly')

    offer = await pc.createOffer()
    await pc.setLocalDescription(offer)

    data = json.dumps({
            "sdp": pc.localDescription.sdp,
            "type": pc.localDescription.type})

    response = requests.post("http://localhost:8080/offer",data=data).json()


    answer = RTCSessionDescription(sdp=response["sdp"],type=response["type"])

    await pc.setRemoteDescription(answer)

    return web.Response(content_type="text/plain", text="Just text")

Результат со службой классификации изображений: RTC Соединение работает с или безподключен к Интернету.

Ожидаемый результат для внешнего интерфейса, но внешнее RTC-соединение не работает без подключения к Интернету.

...