Skip to content

Commit

Permalink
1. small refactoring, sfClient now doesn't know what "channel" is.
Browse files Browse the repository at this point in the history
2. can send multiple chunkIds per request
  • Loading branch information
shacharz committed Feb 12, 2013
1 parent 097a51a commit 049eac5
Show file tree
Hide file tree
Showing 3 changed files with 136 additions and 112 deletions.
110 changes: 62 additions & 48 deletions public/js/peerConnectionImplChrome.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,66 @@
};

peerConnectionImplChrome.prototype = {
//public methods
setupCall:function (peerConnection) {
debug('createOffer with constraints: ' +
JSON.stringify(this.createOfferConstraints, null, ' '));
this.peerConnection.createOffer(
this.setLocalAndSendMessage_,
function (err) {
debug('createOffer(): failed, ' + err)
},
this.createOfferConstraints);
},


handleMessage:function (message) {
message = message.sdp;
console.log('handling message ' + message);
var parsed_msg = JSON.parse(message);
if (parsed_msg.type) {
var session_description = new RTCSessionDescription(parsed_msg);
this.peerConnection.setRemoteDescription(
session_description,
function () {
debug('setRemoteDescription(): success.')
},
function (err) {
debug('setRemoteDescription(): failed, ' + err)
});
if (session_description.type == "offer") {
debug('createAnswer with constraints: ' +
JSON.stringify(this.createAnswerConstraints, null, ' '));
this.peerConnection.createAnswer(
this.setLocalAndSendMessage_,
function (err) {
debug('createAnswer(): failed, ' + err)
},
this.createAnswerConstraints);
}
return;
} else if (parsed_msg.candidate) {
var candidate = new RTCIceCandidate(parsed_msg);
this.peerConnection.addIceCandidate(candidate);
return;
}
addTestFailure("unknown message received");
return;
},

send:function(message){
var thi$ = this;
if (thi$.dataChannel.readyState.toLowerCase() == 'open') {
thi$.dataChannel.send(message);
} else {
console.log('dataChannel wasnt ready, seting timeout');
setTimeout(function (dataChannel, message) {
thi$.send(dataChannel, message);
}, 1000, thi$.dataChannel, message);
}
},

//private methods
initiatePeerConnectionCallbacks:function () {
replaceReturnCallback(function (msg) {
console.log("return log: " + msg);
Expand Down Expand Up @@ -65,12 +124,12 @@
this.onDataChannelReadyStateChange_ = function (event) {
var readyState = event.target.readyState;
debug('DataChannel state:' + readyState);
radio('connectionReady').broadcast(event.target);
radio('connectionReady').broadcast(thi$.targetId);
};

this.onMessageCallback_ = function (message) {
console.log("received message" + message);
radio('commandArrived').broadcast(message.currentTarget, message);
// console.log("received message" + message);
radio('commandArrived').broadcast(message);
};
},

Expand All @@ -84,40 +143,6 @@
this.createDataChannel();
},

handleMessage:function (message) {
message=message.sdp;
console.log('handling message ' + message);
var parsed_msg = JSON.parse(message);
if (parsed_msg.type) {
var session_description = new RTCSessionDescription(parsed_msg);
this.peerConnection.setRemoteDescription(
session_description,
function () {
debug('setRemoteDescription(): success.')
},
function (err) {
debug('setRemoteDescription(): failed, ' + err)
});
if (session_description.type == "offer") {
debug('createAnswer with constraints: ' +
JSON.stringify(this.createAnswerConstraints, null, ' '));
this.peerConnection.createAnswer(
this.setLocalAndSendMessage_,
function (err) {
debug('createAnswer(): failed, ' + err)
},
this.createAnswerConstraints);
}
return;
} else if (parsed_msg.candidate) {
var candidate = new RTCIceCandidate(parsed_msg);
this.peerConnection.addIceCandidate(candidate);
return;
}
addTestFailure("unknown message received");
return;
},

createPeerConnection:function (stun_server) {
servers = {iceServers:[
{url:"stun:" + stun_server}
Expand Down Expand Up @@ -147,17 +172,6 @@
this.peerConnection.ondatachannel = this.onCreateDataChannelCallback_;
},

setupCall:function (peerConnection) {
debug('createOffer with constraints: ' +
JSON.stringify(this.createOfferConstraints, null, ' '));
this.peerConnection.createOffer(
this.setLocalAndSendMessage_,
function (err) {
debug('createOffer(): failed, ' + err)
},
this.createOfferConstraints);
},

createDataChannel:function () {
console.log("createDataChannel");
if (window.webkitRTCPeerConnection)
Expand Down
52 changes: 33 additions & 19 deletions public/js/peerConnectionImplFirefox.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,40 @@
};

peerConnectionImplFirefox.prototype = {
registerEvents:function () {
//public methods
setupCall:function () {
this.initiateCall();
},

handleMessage:function (msg) {
console.log("receivedOffer: " + msg.type);
switch (msg.type) {
case "offer":
this.offererPort = msg.port || 5000;
this.acceptCall(msg.offer, msg.originId);
break;
case "answer":
this.answererPort = msg.port || 5001;
this.incomingAnswer(msg.answer);
break;
}
},

setupCall:function () {
this.initiateCall();
send:function(message){
var thi$ = this;
if (thi$.dataChannel.readyState.toLowerCase() == 'open') {
thi$.dataChannel.send(message)
} else {
console.log('dataChannel wasnt ready, seting timeout');
setTimeout(function (dataChannel, message) {
thi$.send(dataChannel, message);
}, 1000, thi$.dataChannel, message);
}
},

//private methods
registerEvents:function () {

},

initiateCall:function () {
Expand Down Expand Up @@ -74,20 +102,6 @@
};
},

handleMessage:function (msg) {
console.log("receivedOffer: " + msg.type);
switch (msg.type) {
case "offer":
this.offererPort = msg.port || 5000;
this.acceptCall(msg.offer, msg.originId);
break;
case "answer":
this.answererPort = msg.port || 5001;
this.incomingAnswer(msg.answer);
break;
}
},

incomingAnswer:function (answer) {
console.log("incomingAnswer");
var thi$ = this;
Expand Down Expand Up @@ -153,7 +167,7 @@
} else {
// log("message from", remotePC," length=",evt.data.length);
// console.log(evt.data);
radio('commandArrived').broadcast(evt.currentTarget, evt);
radio('commandArrived').broadcast(evt);
}
};

Expand All @@ -166,7 +180,7 @@
thi$.dataChannel.send(proto64.message(thi$.originId, thi$.targetId, greeting));
}
console.log(localPC + "state: " + thi$.dataChannel.state);
radio('connectionReady').broadcast(thi$.dataChannel);
radio('connectionReady').broadcast(thi$.targetId);
};

this.dataChannel.onclose = function () {
Expand Down
86 changes: 41 additions & 45 deletions public/js/sfClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,28 @@
this.peerConnections = {};
this.configureBrowserSpecific();
this.CHUNK_SIZE;//bytes
this.sendingTimeout; //ma
this.peerConnectionImpl;
this.dataChannels = {};
this.initiateClient(wsServerUrl);
this.registerEvents();
this.chunks = {};// <id, arrybuffer>
this.numOfChunksInFile;
this.hasEntireFile = false;
this.incomingChunks = {};
this.requestThresh = 1;
this.numOfChunksToAllocate = 15;
};

client.prototype = {
configureBrowserSpecific:function(){
if(window.mozRTCPeerConnection){
this.CHUNK_SIZE = 50000;
this.sendingTimeout = 1;
this.peerConnectionImpl = peerConnectionImplFirefox;

} else if(window.webkitRTCPeerConnection){
this.CHUNK_SIZE = 750;
this.sendingTimeout = 0;
this.peerConnectionImpl = peerConnectionImplChrome;
}
configureBrowserSpecific:function () {
if (window.mozRTCPeerConnection) {
this.CHUNK_SIZE = 50000;
this.peerConnectionImpl = peerConnectionImplFirefox;

} else if (window.webkitRTCPeerConnection) {
this.CHUNK_SIZE = 750;
this.peerConnectionImpl = peerConnectionImplChrome;
}
},

updateMetadata:function (metadata) {
Expand Down Expand Up @@ -54,13 +54,18 @@
this.checkHasEntireFile();
},

updateProgress:function(){
var percentage = Object.keys(this.chunks).length/this.numOfChunksInFile;
radio('downloadProgress').broadcast(percentage*100);
updateProgress:function () {
var percentage = Object.keys(this.chunks).length / this.numOfChunksInFile;
radio('downloadProgress').broadcast(percentage * 100);
},

requestChunks:function (dataChannel, chunkNum) {
this.sendCommand(dataChannel, proto64.need(this.clientId, 1, 1, chunkNum));
requestChunks:function (targetId) {
var chunkIds = [];
for(var i=0;i<this.numOfChunksToAllocate && (Object.keys(this.chunks).length + i)<this.numOfChunksInFile;++i){
chunkIds.push(Object.keys(this.chunks).length + i);
}
this.incomingChunks[targetId]+=chunkIds.length;
this.peerConnections[targetId].send(proto64.need(this.clientId, 1, 1, chunkIds))
},

checkHasEntireFile:function () {
Expand Down Expand Up @@ -90,21 +95,7 @@
//init true if this peer initiated the connection
ensureHasPeerConnection:function (peerId, init) {
if (!this.peerConnections[peerId]) {
this.peerConnections[peerId] = new this.peerConnectionImpl(this.ws,this.clientId, peerId, init);
}
},

sendCommand:function (dataChannel, message) {
var thi$ = this;
if (dataChannel.readyState.toLowerCase() == 'open') {
setTimeout(function (message) { //setting a timeout since chrome can't handle fast transfer yet
dataChannel.send(message)
}, this.sendingTimeout, message);
} else {
console.log('dataChannel wasnt ready, seting timeout');
setTimeout(function (dataChannel, message) {
thi$.sendCommand(dataChannel, message);
}, 1000, dataChannel, message);
this.peerConnections[peerId] = new this.peerConnectionImpl(this.ws, this.clientId, peerId, init);
}
},

Expand All @@ -120,7 +111,7 @@
}, this]);

radio('receivedMatch').subscribe([function (message) {
if(this.hasEntireFile)
if (this.hasEntireFile)
return;
for (var i = 0; i < message.clientIds.length; ++i) {
this.ensureHasPeerConnection(message.clientIds[i], true);
Expand All @@ -134,31 +125,36 @@
}, this]);

//PeerConnection events
radio('commandArrived').subscribe([function (dataChannel, msg) {
radio('commandArrived').subscribe([function (msg) {
var cmd = proto64.decode(msg.data);
if (cmd.op == proto64.NEED_CHUNK) {
console.log("received NEED_CHUNK command " + cmd.chunkId);
if (cmd.chunkId in this.chunks) {
this.sendCommand(dataChannel, proto64.send(this.clientId, 1, 1, cmd.chunkId, this.chunks[cmd.chunkId]))
} else {
console.warn('I dont have this chunk' + cmd.chunkId);
for (var i = 0; i < cmd.chunkId.length; ++i) {
var chunkId = cmd.chunkId[i];
// console.log("received NEED_CHUNK command " + chunkId);
if (chunkId in this.chunks) {
this.peerConnections[cmd.originId].send(proto64.send(this.clientId, 1, 1, chunkId, this.chunks[chunkId]));
} else {
console.warn('I dont have this chunk' + chunkId);
}
}
} else if (cmd.op == proto64.DATA_TAG) {
console.log("received DATA_TAG command with chunk id " + cmd.chunkId);
// console.log("received DATA_TAG command with chunk id " + cmd.chunkId);
this.receiveChunk(cmd.chunkId, cmd.data);
if (!this.hasEntireFile)
this.requestChunks(dataChannel, cmd.chunkId + 1);
} else if(cmd.op == proto64.MESSAGE) {
this.incomingChunks[cmd.originId]--;
if (!this.hasEntireFile && this.incomingChunks[cmd.originId] < this.requestThresh)
this.requestChunks(cmd.originId);
} else if (cmd.op == proto64.MESSAGE) {
console.log("peer " + cmd.originId + " sais: " + cmd.data);
}
}, this]);

radio('connectionReady').subscribe([function (dataChannel) {
radio('connectionReady').subscribe([function (targetId) {
this.incomingChunks[targetId] = 0;
if (0 in this.chunks) {
console.log('got chunk 0');
} else {
console.log('requesting chunk 0');
this.requestChunks(dataChannel, 0);
this.requestChunks(targetId);
}
}, this]);

Expand Down

0 comments on commit 049eac5

Please sign in to comment.