Presented by Shih-En Chou
為什麼Logo五彩繽紛?
Client opens connection with server
Client and server send data to each other as data becomes available on either side
var connection = new WebSocket('ws://subdomain.examnple.com/some-endpoint')
connection.onopen = function(e) {
console.log("Connected");
};
connection.onmessage = function(e) {
console.log( "Received: " + e.data);
};
connection.onclose = function(e) {
console.log("Connection closed");
};
connection.send("這是伺服器正迫切需要的文字!");
WebSockets is cross-domain by default
Up to you to optionally restrict domain access on server via Origin
header
Built-in method for defining WebSocket extensions via RFC
Current extensions include perframe-deflate and multiplexing
Using ws
in production can cause WebSockets communication to fail due to invisible proxies that can't do WebSockets
Using wss
forces browser to issue HTTP_CONNECT
statement to proxy server, which sets up tunnel
So use wss
in production
已經做出限定Event, 讓Message 根據Bind Event來傳遞訊息
pc = new RTCPeerConnection(configuration);
pc.onnegotiationneeded = function () {
pc.createOffer(localDescCreated, logError);
}
//offer
pc.setLocalDescription(desc, function () {
socket.emit('sendrtc', JSON.stringify({
'sdp': pc.localDescription
}));
}, logError);
//answer
pc.setRemoteDescription(new RTCSessionDescription(message.sdp),
function () {
// if we received an offer, we need to answer
if (pc.remoteDescription.type == 'offer')
pc.createAnswer(localDescCreated, logError);
}, logError);
//Candidate:
pc.addIceCandidate(new RTCIceCandidate(message.candidate));
HTML5 有了Blob API
直接把WebSocket 與Blob 接起來就好了
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
binary[i] = img.data[i];
}
connection.send(binary.buffer);
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);
WebSockets | WebRTC |
---|---|
方便broadcast | 1-to-1 Connection |
傳文字, blob | 傳stream |
方便debug | 不易找錯... |
offerer = new RTCPeerConnection(configuration);
var channel = offerer.createDataChannel('RTCDataChannel', {
reliable: false
});
channel.onmessage = function (event) {
console.debug(channelNameForConsoleOutput,
'received a message:', event.data);
};
channel.onopen = function () {
channel.send('first text message over RTP data ports');
};
channel.send("Hello Server!");