我有一个项目,我试图在没有互联网的情况下使用 UDP over LAN 与 WebRTC 聊天。
我的代码基于此视频:https://www.youtube.com/watch?v=hAKQzNQmNe0
我的代码如何工作:
firebase
创建了视频聊天。成功了!OpenUserMedia
、createRoom
、joinRoom
和hangUp
。OpenUserMedia
和hangUp
完好无损。所以我希望他们完美无缺。createRoom
管理调用方,joinRoom
管理被调用方。firebase
通信替换为 UDP 通信。sendMessage
通过 UDP 发送数据,而 listenForMessage
每当有消息到来时都会接收数据。通讯正常。createRoom
使用 ICECandidate
和 Offer
发送消息。joinRoom
确实会收到带有 ICECandidate
(来电者候选人)和 Offer
的消息。
Future<void> joinRoom(String roomId, RTCVideoRenderer remoteVideo) async {
// print('Create PeerConnection with configuration: $configuration');
peerConnection = await createPeerConnection(configuration);
registerPeerConnectionListeners();
localStream?.getTracks().forEach((track) {
peerConnection?.addTrack(track, localStream!);
});
// Code for collecting ICE candidates below
peerConnection!.onIceCandidate = (RTCIceCandidate? candidate) {
if (candidate == null) {
// print('onIceCandidate: complete!');
return;
}
Communicating.sendMessage(
{'type': 'calleeCandidates', 'data': candidate.toMap()});
calleeCandidates.add(candidate.toMap());
// addMyCandidate(candidate.toMap());
};
// Code for collecting ICE candidate above
peerConnection?.onTrack = (RTCTrackEvent event) {
// print('Got remote track: ${event.streams[0]}');
event.streams[0].getTracks().forEach((track) {
// print('Add a track to the remoteStream: $track');
remoteStream?.addTrack(track);
});
};
Communicating.listenForMessage((responseMessage) async {
var data = responseMessage['data'];
// Code for creating SDP answer below
if (responseMessage['type'] == 'offer') {
// print('Got offer $data');
var offer = data['offer'];
await peerConnection?.setRemoteDescription(
RTCSessionDescription(offer['sdp'], offer['type']),
);
var answer = await peerConnection!.createAnswer();
// print('Created Answer $answer');
await peerConnection!.setLocalDescription(answer);
Map<String, dynamic> roomWithAnswer = {
'answer': {'type': answer.type, 'sdp': answer.sdp}
};
Communicating.sendMessage({'type': 'offer', 'data': roomWithAnswer});
// Finished creating SDP answer
// Listen for remote Ice candidates below
} else if (responseMessage['type'] == 'callerCandidates') {
peerConnection!.addCandidate(
RTCIceCandidate(
data['candidate'],
data['sdpMid'],
data['sdpMLineIndex'],
),
);
}
});
}
我的问题是当
joinRoom
方法收到带有报价类型的消息时。它进入 if (responseMessage['type'] == 'offer') {
内部,但在调用 setRemoteDescription
方法后离开。 (下面的代码与上面相同)
await peerConnection?.setRemoteDescription(
RTCSessionDescription(offer['sdp'], offer['type']),
);
这意味着它永远不会调用
await peerConnection!.createAnswer();
。
它不会抛出任何异常。
为什么它从不执行
if (responseMessage['type'] == 'offer')
中的最后 3 个命令?我是不是错过了什么?