我正在尝试使用 WebRTC 数据通道将从画布捕获的图像发送到我的 NodeJS 后端服务器。那就是我试图让我的服务器成为对等点。但由于某种原因,我无法建立连接。
客户端
async function initChannel()
{
const offer = await peer.createOffer();
await peer.setLocalDescription(offer);
const response = await fetch("/connect", {
headers: {
'Content-Type': 'application/json',
},
method: 'post',
body: JSON.stringify({ sdp: offer, id: Math.random() })
}).then((res) => res.json());
peer.setRemoteDescription(response.sdp);
const imageChannel = peer.createDataChannel("imageChannel", { ordered: false, maxPacketLifeTime: 100 });
peer.addEventListener("icecandidate", console.log);
peer.addEventListener("icegatheringstatechange",console.log);
// drawCanvas function draws images got from the server.
imageChannel.addEventListener("message", message => drawCanvas(remoteCanvasCtx, message.data, imageChannel));
// captureImage function captures and sends image to server using imageChannel.send()
imageChannel.addEventListener("open", () => captureImage(recordCanvasCtx, recordCanvas, imageChannel));
}
const peer = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.stunprotocol.org:3478" }] });
initChannel();
这里两者captureImage
都drawCanvas
没有被调用。
服务器端
import webrtc from "wrtc"; // The wrtc module ( npm i wrtc )
function handleChannel(channel)
{
console.log(channel.label); // This function is not being called.
}
app.use(express.static(resolve(__dirname, "public")))
.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true }));
app.post("/connect", async ({ body }, res) =>
{
console.log("Connecting to client...");
let answer, id = body.id;
const peer = new webrtc.RTCPeerConnection({ iceServers: [{ urls: "stun:stun.stunprotocol.org:3478" }] });
await peer.setRemoteDescription(new webrtc.RTCSessionDescription(body.sdp));
await peer.setLocalDescription(answer = await peer.createAnswer());
peer.addEventListener("datachannel",handleChannel)
return res.json({ sdp: answer });
});
app.listen(process.env.PORT || 2000);
在这里,post 请求处理得很好,但从handleChannel
未被调用。
当我运行它时,我没有收到任何错误,但是当我检查连接状态时,它永远显示“新”。我控制台记录了远程和本地描述,它们似乎都设置好了。我在这里做错了什么?
我对 WebRTC 很陌生,我什至不确定这是否是从服务器连续发送图像(用户网络摄像头的帧)和从服务器返回的正确方法,如果有人能告诉我更好的方法,请这样做。
canvas.toBlob()
还有一件事,我怎样才能通过数据通道以低延迟发送图像 blob(从)。