How to write unit test component with FileReader.addEventListener in angular 8? - karma-jasmine

I use angular 8 and i want to test my component with FileReader.
I can not test a FileReader in my processFile function.
Maybe my work is badly written? Can you help me please to understand.
IF I understand correctly, I have to test a class (Filereader) in a process function
my component
processFile(imageInput: any) {
const file: File = imageInput.files[0];
const reader = new FileReader();
let size: number = 2097152
if (file) {
if (file.size <= size) {
this.sharingDataService.setUploadIsOk(true)
reader.addEventListener('progress', (event:any) =>{
this.progressValue = this.progressBar(event)
if (event.lengthComputable) {
// console.log(event.loaded+ " / " + event.total)
}
})
reader.addEventListener('loadstart', (event:any) =>{
this.progressValue =0;
this.textDuringUploadBefore = "No"
this.textDuringUploadAfter = ''
// console.log('start');
})
reader.addEventListener('loadend', (event:any) =>{
// console.log('end');
})
reader.addEventListener('load', (event: any) => {
console.log(event);
this.selectedFile = new ImageSnippet(event.target.result, file);
this.fileName = this.selectedFile.file.name;
this.fileNameExt =this.fileName.split('.').pop();
this.displayAddPhoto = false;
this.selectedFile.status = 'ok';
this.getLoadCallBack(file)
// this.ng2ImgMax.resizeImage(file, 900,600).subscribe(
// result =>{
// // console.log('compress', );
// this.textDuringUploadAfter= "Yes!!!"
// this.textDuringUploadBefore= ''
// this.fileForm.patchValue({
// image: new File([result], result.name)
// });
// this.imageIsLoad = true
// this.sharingDataService.setUploadIsOk(false)
// }
// )
// this.imageOutput.emit(this.fileForm)
});
reader.readAsDataURL(file);
} else {
const msg ="This picture is too big."
+ '<br/>' + "Please upload an image of less than 2MB."
// this.sharedFunctionService.openDialogAlert(msg, 'home')
this.errorService.openDialogError(msg)
this.imageIsLoad = false
this.sharingDataService.setUploadIsOk(false)
}
}
}
getLoadCallBack(file:File){
this.ng2ImgMax.resizeImage(file, 900,600).subscribe(
result =>{
// console.log('compress', );
this.textDuringUploadAfter= "Yes"
this.textDuringUploadBefore= ''
this.fileForm.patchValue({
image: new File([result], result.name)
});
console.log(this.fileForm);
this.imageIsLoad = true
this.sharingDataService.setUploadIsOk(false)
}
)
this.imageOutput.emit(this.fileForm)
}
my spec.ts
it('processFile', () => {
// const mockEvt = { target: { files: [fileInput] } };
// const mockReader: FileReader = jasmine.createSpyObj('FileReader', ['readAsDataURL', 'onload']);
// spyOn(window as any, 'FileReader').and.returnValue(mockReader);
// spyOn(component, 'getLoadCallBack').and.callThrough();
const file = new File([''], 'test-file.jpg', { lastModified: null, type: 'image/jpeg' });
const fileInput = { files: [file] };
const eventListener = jasmine.createSpy();
spyOn(window as any, "FileReader").and.returnValue({
addEventListener: eventListener
})
component.processFile(fileInput);
i have got an error
TypeError: reader.readAsDataURL is not a function
how to test my processFile function?
I trie many way but no sucess

Related

Getting "spc message cannot be null" as response

Getting "spc message cannot be null" as response every time while providing implementation of Shaka player to play fairplay content on safari browser.Tried many ways to provide spc message in body and header also and we are actually sending it that i can see in network tab nut still cant find a solution. Here is the code below.
if (this.platform.getBrowserPlatform() === Constants.PLATFORMS.SAFARI_WEB) {
this.shakaPlayer.configure({
drm: {
servers: {
'com.apple.fps.1_0': `${this.config.baseUrl}${Constants.DRM_FAIRPLAY_LICENSE}`,
},
advanced: {
'com.apple.fps.1_0': {
serverCertificate: cert,
},
},
},
});
let that = this //,licenseUri;
this.shakaPlayer.configure('drm.initDataTransform', (initData) => {
const skdUri = shaka.util.StringUtils.fromBytesAutoDetect(initData);
var contentId = skdUri.substring(skdUri.indexOf('skd://') + 6);
// licenseUri = skdUri.replace('skd://', 'https://');
const url = new URL(contentId);
const urlParams = new URLSearchParams(url.search);
const cert = that.shakaPlayer.drmInfo().serverCertificate;
let id = urlParams.get('contentId');
that.id = id;
return shaka.util.FairPlayUtils.initDataTransform(initData, id, cert);
// let skdUrl = shaka.util.StringUtils.fromBytesAutoDetect(initData);
// licenseUri = skdUrl.replace('skd://', 'https://');
// const cert = that.shakaPlayer.drmInfo().serverCertificate;
// return shaka.util.FairPlayUtils.initDataTransform(initData, licenseUri, cert);
});
this.shakaPlayer.getNetworkingEngine().registerRequestFilter((type, request) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
let token = localStorage.getItem('auth');
let testToken = JSON.parse(token);
const originalPayload = new Uint8Array(request.body);
const base64Payload = shaka.util.Uint8ArrayUtils.toBase64(originalPayload);
const params = `{ "spc": "${base64Payload}", "assetId":"${that.id}"}`;
request.body = shaka.util.StringUtils.toUTF8(params);
request.headers['Content-Type'] = 'application/json';
request.headers['Authorization'] = `JWT ${testToken.access_token}`
console.log("request.body", request.body)
});
this.shakaPlayer.getNetworkingEngine().registerResponseFilter((type, response) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
console.log("license passed")
let responseText = shaka.util.StringUtils.fromUTF8(response.data);
responseText = responseText.trim();
if (responseText.substr(0, 5) === '<ckc>' &&
responseText.substr(-6) === '</ckc>') {
responseText = responseText.slice(5, -6);
}
response.data = shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
});
this.shakaPlayer.load(this.getProgramUrl(channel, program, restart)).then(() => {
console.log('1', this.shakaPlayer.isTextTrackVisible());
console.log('2', this.shakaPlayer.getTextTracks());
console.log('3', this.shakaPlayer.getTextLanguages());
}).catch((error) => {
console.log(error);
});
Smooth play of fairplay content on safari or some advise what can i do in this case

Error integrating Agora.io with nuxt.js Error in created hook: "ReferenceError: AgoraRTC is not defined"

I am integrating Agora Web SDK with nuxt.js.
I have included all the methods I need and my page has the following methods and lifecycle hooks:
methods: {
streamInit(uid, attendeeMode, videoProfile, config) {
let defaultConfig = {
streamID: uid,
audio: true,
video: true,
screen: false
};
switch (attendeeMode) {
case "audio-only":
defaultConfig.video = false;
break;
case "audience":
defaultConfig.video = false;
defaultConfig.audio = false;
break;
default:
case "video":
break;
}
let stream = AgoraRTC.createStream(merge(defaultConfig, config));
stream.setVideoProfile(videoProfile);
return stream;
},
subscribeStreamEvents() {
let rt = this;
rt.client.on("stream-added", function(evt) {
let stream = evt.stream;
console.log("New stream added: " + stream.getId());
console.log("At " + new Date().toLocaleTimeString());
console.log("Subscribe ", stream);
rt.client.subscribe(stream, function(err) {
console.log("Subscribe stream failed", err);
});
});
rt.client.on("peer-leave", function(evt) {
console.log("Peer has left: " + evt.uid);
console.log(new Date().toLocaleTimeString());
console.log(evt);
rt.removeStream(evt.uid);
});
rt.client.on("stream-subscribed", function(evt) {
let stream = evt.stream;
console.log("Got stream-subscribed event");
console.log(new Date().toLocaleTimeString());
console.log("Subscribe remote stream successfully: " + stream.getId());
console.log(evt);
rt.addStream(stream);
});
rt.client.on("stream-removed", function(evt) {
let stream = evt.stream;
console.log("Stream removed: " + stream.getId());
console.log(new Date().toLocaleTimeString());
console.log(evt);
rt.removeStream(stream.getId());
});
},
removeStream(uid) {
this.streamList.map((item, index) => {
if (item.getId() === uid) {
item.close();
let element = document.querySelector("#ag-item-" + uid);
if (element) {
element.parentNode.removeChild(element);
}
let tempList = [...this.streamList];
tempList.splice(index, 1);
this.streamList = tempList;
}
});
},
addStream(stream, push = false) {
let repeatition = this.streamList.some(item => {
return item.getId() === stream.getId();
});
if (repeatition) {
return;
}
if (push) {
this.streamList = this.streamList.concat([stream]);
} else {
this.streamList = [stream].concat(this.streamList);
}
},
handleCamera(e) {
e.currentTarget.classList.toggle("off");
this.localStream.isVideoOn()
? this.localStream.disableVideo()
: this.localStream.enableVideo();
},
handleMic(e) {
e.currentTarget.classList.toggle("off");
this.localStream.isAudioOn()
? this.localStream.disableAudio()
: this.localStream.enableAudio();
},
switchDisplay(e) {
if (
e.currentTarget.classList.contains("disabled") ||
this.streamList.length <= 1
) {
return;
}
if (this.displayMode === "pip") {
this.displayMode = "tile";
} else if (this.displayMode === "tile") {
this.displayMode = "pip";
} else if (this.displayMode === "share") {
// do nothing or alert, tbd
} else {
console.error("Display Mode can only be tile/pip/share");
}
},
hideRemote(e) {
if (
e.currentTarget.classList.contains("disabled") ||
this.streamList.length <= 1
) {
return;
}
let list;
let id = this.streamList[this.streamList.length - 1].getId();
list = Array.from(
document.querySelectorAll(`.ag-item:not(#ag-item-${id})`)
);
list.map(item => {
if (item.style.display !== "none") {
item.style.display = "none";
} else {
item.style.display = "block";
}
});
},
handleExit(e) {
if (e.currentTarget.classList.contains("disabled")) {
return;
}
try {
this.client && this.client.unpublish(this.localStream);
this.localStream && this.localStream.close();
this.client &&
this.client.leave(
() => {
console.log("Client succeed to leave.");
},
() => {
console.log("Client failed to leave.");
}
);
} finally {
this.readyState = false;
this.client = null;
this.localStream = null;
// redirect to index
this.$router.push("/");
}
}
},
created() {
let $ = this;
// init AgoraRTC local client
$.client = AgoraRTC.createClient({ mode: $.transcode });
$.client.init($.appId, () => {
console.log("AgoraRTC client initialized");
$.subscribeStreamEvents();
$.client.join($.appId, $.channel, $.uid, uid => {
console.log("User " + uid + " join channel successfully");
console.log("At " + new Date().toLocaleTimeString());
// create local stream
// It is not recommended to setState in function addStream
$.localStream = this.streamInit(uid, $.attendeeMode, $.videoProfile);
$.localStream.init(
() => {
if ($.attendeeMode !== "audience") {
$.addStream($.localStream, true);
$.client.publish($.localStream, err => {
console.log("Publish local stream error: " + err);
});
}
$.readyState = true;
},
err => {
console.log("getUserMedia failed", err);
$.readyState = true;
}
);
});
});
},
mounted() {
this.$nextTick(() => {
// add listener to control btn group
let canvas = document.querySelector("#ag-canvas");
let btnGroup = document.querySelector(".ag-btn-group");
canvas.addEventListener("mousemove", () => {
if (global._toolbarToggle) {
clearTimeout(global._toolbarToggle);
}
btnGroup.classList.add("active");
global._toolbarToggle = setTimeout(function() {
btnGroup.classList.remove("active");
}, 2000);
});
});
},
beforeUpdate() {
let $ = this;
// rerendering
let canvas = document.querySelector("#ag-canvas");
// pip mode (can only use when less than 4 people in channel)
if ($.displayMode === "pip") {
let no = $.streamList.length;
if (no > 4) {
$.displayMode = "tile";
return;
}
$.streamList.map((item, index) => {
let id = item.getId();
let dom = document.querySelector("#ag-item-" + id);
if (!dom) {
dom = document.createElement("section");
dom.setAttribute("id", "ag-item-" + id);
dom.setAttribute("class", "ag-item");
canvas.appendChild(dom);
item.play("ag-item-" + id);
}
if (index === no - 1) {
dom.setAttribute("style", `grid-area: span 12/span 24/13/25`);
} else {
dom.setAttribute(
"style",
`grid-area: span 3/span 4/${4 + 3 * index}/25;
z-index:1;width:calc(100% - 20px);height:calc(100% - 20px)`
);
}
item.player.resize && item.player.resize();
});
} else if ($.displayMode === "tile") {
// tile mode
let no = $.streamList.length;
$.streamList.map((item, index) => {
let id = item.getId();
let dom = document.querySelector("#ag-item-" + id);
if (!dom) {
dom = document.createElement("section");
dom.setAttribute("id", "ag-item-" + id);
dom.setAttribute("class", "ag-item");
canvas.appendChild(dom);
item.play("ag-item-" + id);
}
dom.setAttribute("style", `grid-area: ${tile_canvas[no][index]}`);
item.player.resize && item.player.resize();
});
} else if ($.displayMode === "share") {
// screen share mode (tbd)
}
},
beforeDestroy () {
this.client && this.client.unpublish(this.localStream);
this.localStream && this.localStream.close();
this.client &&
this.client.leave(
() => {
console.log("Client succeed to leave.");
},
() => {
console.log("Client failed to leave.");
}
);
}
I have installed agora-rtc-sdk from npm.
My plugins/agora.js file looks like this
import Vue from "vue";
import AgoraRTC from 'agora-rtc-sdk';
Vue.use(AgoraRTC);
My nuxt.config.js has plugins declared as:
{
src: "~/plugins/agora.js",
ssr: false
}
The application on loading the page gives AgoraRTC is not defined. How do I add this AgoraRTC to my nuxt.js application?
Agora works only on the client side, fully independent of a server and hence you need to define the mode as client in the nuxt.config.js like this:
{ src: '~/plugins/agora.js', mode: 'client' },

ngx-dropzone to load images from list

I am using ngx-dropzone with angular 8. I have used ngx-dropzone for uploading and it works but this time I want to load images from a specific list to dropzone. Here is my code.
<ngx-dropzone (change)="onSelect($event)">
<ngx-dropzone-label>Select/Drop images here!</ngx-dropzone-label>
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" [removable]="true" (removed)="onRemove(f)" *ngFor="let f of files" [file]="f">
<ngx-dropzone-label></ngx-dropzone-label>
</ngx-dropzone-image-preview>
</ngx-dropzone>
Here is my onSelect event which bindimages and push them into files array list.
onSelect(event) {
this.alertService.clear();
console.log(event.addedFiles);
this.files.push(...event.addedFiles);
if (this.files.length > 4) {
this.alertService.error('Please select only four images for each service.');
this.files = [];
} else {
this.bindImages();
}
}
bindImages() {
this.alertService.clear();
this.imageList = [];
this.files.forEach((x) => {
const file = x;
if (file.type.split('/')[0] !== 'image') {
this.alertService.error('Please select image to proceed further.');
return false;
}
if (file.size > 5242880) {
this.alertService.error('Image size must be equal to or less then 5 MB.');
return false;
}
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const val = reader.result as string;
const items = [{Serviceimage: val, ServiceId: this.serviceId, SaloonId: this.saloonId}];
this.imageList.push(...items);
};
reader.onerror = (error) => {
console.log('Error: ', error);
return;
};
});
}
Here is the my api codes which returns me the list of images with base64 string
getImages() {
this.alertService.clear();
this.imageModel.SaloonId = this.saloonId;
this.imageModel.ServiceId = this.serviceId;
this.apiService.Create('Saloon/getServiceImages', this.imageModel).subscribe(
resp => {
if (resp.length > 0) {
// Here to load Images to dropzone.
}
console.log(this.files);
},
error => {
this.alertService.error('Error getting images. Please contact admin.');
},
() => { console.log('complete'); }
);
}
This image returns me the following list.

angular 8- webrtc-adapter in Firefox not working

I try to run poc which created in angular 8 using webrtc-adpater. Problem is that it is not working in firefox and safari, but working in chrome.
What I observe connection is never connecting or connected in firefox.
I import webrtc in code so anything else we need to handle for firefox and safari.
Basically from Wowza I trying to consume streaming.
Below code sample which working in chrome but not in Firefox and safari:
const ICE_SERVERS: RTCIceServer[] = [
{ urls: ['stun:stun.example.com', 'stun:stun-1.example.com'] },
{ urls: 'stun:stun.l.google.com:19302' }
];
setupSignalingServer(ele) {
const self = this;
window.RTCPeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
let signalingConnection = new WebSocket('wss://local.geofabricdev.com/webrtc-session.json');
signalingConnection.binaryType = 'arraybuffer';
signalingConnection.onopen = function (res) {
console.log('connection open');
signalingConnection.onerror = self.errorHandler;
// window.RTCPeerConnection = self.getRTCPeerConnection();
const peerConnection = new RTCPeerConnection(PEER_CONNECTION_CONFIG);
peerConnection.addEventListener('connectionstatechange', event => {
console.log(event);
if (peerConnection.connectionState === 'connected') {
console.log('connected');
}
});
peerConnection.addEventListener('icecandidate', event => {
console.log('peerconnection state5:' + peerConnection.connectionState);
if (event.candidate) {
// signalingChannel.send({'new-ice-candidate': event.candidate});
}
});
peerConnection.addEventListener('track', async event => {
console.log('gotRemoteTrack: kind:' + event.track.kind + ' stream:' + event.streams[0]);
const video = self.createVideo();
// const remoteVideo1 = document.querySelector('#remoteVideo') as HTMLVideoElement;
try {
video.srcObject = event.streams[0];
// remoteVideo1.srcObject = event.streams[0];
} catch (error) {
video.src = window.URL.createObjectURL(event.streams[0]);
}
});
signalingConnection.addEventListener('message', async message => {
console.dir(message);
// self.getSignalMessageCallback(message);
console.log('wsConnection.onmessage: ' + message.data);
const signal = JSON.parse(message.data);
if(signal.status !== 200) {
const video = self.createVideo();
video.poster = '../assets/streaming-error.png';
}
const streamInfoResponse = signal['streamInfo'];
let g = [];
// self.socketStream.some((f) => {
g = self.streams.filter((str) => signal['streamInfo'].streamName === str.streamName);
// if(g.length > 0) {
// return true;
// }
// });
// });
if (streamInfoResponse !== undefined) {
g[0]['sessionId'] = streamInfoResponse.sessionId;
}
console.log('Received signal');
const msgCommand = signal['command'];
console.log(msgCommand);
if (signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp));
if (signal.sdp) {
const description = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(description);
signalingConnection.send('{"direction":"play", "command":"sendResponse", "streamInfo":' +
JSON.stringify(g[0]) + ', "sdp":' + JSON.stringify(description) + ',"userData":' + JSON.stringify(self.userData) + '}');
}
// })
// .catch(self.errorHandler);
} else if (signal.iceCandidates) {
console.log('ice: ' + JSON.stringify(signal.iceCandidates));
peerConnection.addIceCandidate(new RTCIceCandidate(signal.iceCandidates[0])).catch(self.errorHandler);
}
if ('sendResponse'.localeCompare(msgCommand) === 0) {
if (signalingConnection != null) {
signalingConnection.close();
}
signalingConnection = null;
}
// };
});
signalingConnection.send('{"direction":"play", "command":"getOffer", "streamInfo":' +
JSON.stringify(ele) + ', "userData":' + JSON.stringify(self.userData) + '}');
};
signalingConnection.onclose = function (r) {
console.log('close');
};
}
private createVideo() {
const video = document.createElement('video');
video.classList.add('cameraPanel');
video.autoplay = true;
video.preload = 'true';
video.muted = true;
video.width = 300;
const remoteVideo = document.querySelector('#videoContainer') as HTMLElement;
remoteVideo.appendChild(video);
return video;
}

WebRTC DataChannel Errors

I'm trying to connect 2 peers with webrtc and datachannel without camera and microphone.
try {
socket = new WebSocket("ws://localhost:1337/");
var servers = {iceServers:[{url:"stun:stun.l.google.com:19302"}]};
peerConn = new webkitRTCPeerConnection(servers, {optional:[{RtpDataChannels: true}]});
channel = peerConn.createDataChannel("abcd1234", {reliable: false});
peerConn.onicecandidate = function(evt) {
if(evt.candidate) {
socket.send(JSON.stringify({"candidate": evt.candidate}));
}
};
channel.onopen = function () {
console.log("channel is open");
channel.send('first text message over RTP data ports');
};
channel.onmessage = function (event) {
console.log('received a message:', event.data);
};
peerConn.createOffer(function(desc) {
peerConn.setLocalDescription(desc);
socket.send(JSON.stringify({"sdp": desc}));
});
socket.onmessage = function(evt) {
var signal = JSON.parse(evt.data);
if(signal.sdp) {
peerConn.setRemoteDescription(new RTCSessionDescription(signal.sdp));
alert("desc");
} else {
peerConn.addIceCandidate(new RTCIceCandidate(signal.candidate));
alert("ice");
}
}
} catch(e) {
console.log(e.message);
}
In Chrome this errors out with:
Uncaught Error: InvalidStateError: DOM Exception 11
Open two tabs; click "Create Offer" button from 1st tab; and watch console logs:
<script>
// webkitRTCPeerConnection && RTCDataChannel specific code goes here
var iceServers = {
iceServers: [{
url: 'stun:stun.l.google.com:19302'
}]
};
var optionalRtpDataChannels = {
optional: [{
RtpDataChannels: true
}]
};
var mediaConstraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: false, // Hmm!!
OfferToReceiveVideo: false // Hmm!!
}
};
var offerer, answerer, answererDataChannel, offererDataChannel;
function createOffer() {
offerer = new webkitRTCPeerConnection(iceServers, optionalRtpDataChannels);
offererDataChannel = offerer.createDataChannel('RTCDataChannel', {
reliable: false
});
setChannelEvents(offererDataChannel, 'offerer');
offerer.onicecandidate = function (event) {
if (!event.candidate) returnSDP();
};
offerer.ongatheringchange = function (event) {
if (event.currentTarget && event.currentTarget.iceGatheringState === 'complete') returnSDP();
};
function returnSDP() {
socket.send({
sender: 'offerer',
sdp: offerer.localDescription
});
}
offerer.createOffer(function (sessionDescription) {
offerer.setLocalDescription(sessionDescription);
}, null, mediaConstraints);
}
function createAnswer(offerSDP) {
answerer = new webkitRTCPeerConnection(iceServers, optionalRtpDataChannels);
answererDataChannel = answerer.createDataChannel('RTCDataChannel', {
reliable: false
});
setChannelEvents(answererDataChannel, 'answerer');
answerer.onicecandidate = function (event) {
if (!event.candidate) returnSDP();
};
answerer.ongatheringchange = function (event) {
if (event.currentTarget && event.currentTarget.iceGatheringState === 'complete') returnSDP();
};
function returnSDP() {
socket.send({
sender: 'answerer',
sdp: answerer.localDescription
});
}
answerer.setRemoteDescription(new RTCSessionDescription(offerSDP));
answerer.createAnswer(function (sessionDescription) {
answerer.setLocalDescription(sessionDescription);
}, null, mediaConstraints);
}
function setChannelEvents(channel, channelNameForConsoleOutput) {
channel.onmessage = function (event) {
console.debug(channelNameForConsoleOutput, 'received a message:', event.data);
};
channel.onopen = function () {
channel.send('first text message over RTP data ports');
};
}
// WebSocket specific code goes here
var socket = new WebSocket('ws://localhost:1337');
socket.onmessage = function (e) {
var data = JSON.parse(e.data);
console.log(data);
if (data.sdp) {
if (data.sender == 'offerer') createAnswer(data.sdp);
else offerer.setRemoteDescription(new RTCSessionDescription(data.sdp));
}
};
socket.push = socket.send;
socket.send = function (data) {
socket.push(JSON.stringify(data));
};
</script>
<button id="create-offer">Create Offer</button>
<script>
document.getElementById('create-offer').onclick = function () {
this.disabled = true;
createOffer();
};
</script>
now i'm trying the following:
First i create an offer on client #1 and send the description:
try {
peerConn = new webkitRTCPeerConnection(stunServers, {optional:[{RtpDataChannels: true}]});
peerConn.createOffer(function(desc) {
peerConn.setLocalDescription(desc);
socket.send("createpeer|" + JSON.stringify(desc));
}, null, mediaConstraints);
peerConn.onconnection = function () {
console.log("[webrtc] connected with peer");
peerChannel = peerConn.createDataChannel("test", {reliable: false});
peerChannel.onmessage = function (event) {
alert("Server: " + event.data);
};
peerChannel.onopen = function () {
peerChannel.send("Hello Server!");
};
};
} catch(error) {
console.log(error);
}
Client #2 receives that and sends his description:
case "createpeer":
console.log("[websocket] received create peer request from " + cmd[1] + " on " + cmd[2]);
try {
peerConn = new webkitRTCPeerConnection(stunServers, {optional:[{RtpDataChannels: true}]});
peerConn.setRemoteDescription(new RTCSessionDescription(JSON.parse(cmd[3])));
peerConn.createAnswer(function(desc) {
peerConn.setLocalDescription(desc);
socket.send("openpeer|" + cmd[1] + "|" + cmd[2] + "|" + JSON.stringify(desc));
}, null, mediaConstraints);
peerConn.ondatachannel = function (channel) {
channel.onmessage = function (event) {
alert("Client: " + event.data);
};
channel.onopen = function () {
channel.send("Hello Client!");
};
};
} catch(error) {
console.log(error);
}
break;
Finally client #1 recives the description from client #2
case "openpeer":
console.log("[websocket] received open peer");
peerConn.setRemoteDescription(new RTCSessionDescription(JSON.parse(cmd[1])));
break;
Everything works fine without errors, but the connection is not established and the onconnection method is not called.
Greetings