我的剧本:
var srgt_socket = false;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
window.srgt_socket = new WebSocket("ws://185.25.150.192:1987");
window.srgt_socket.addEventListener('open', function (event) {
window.srgt_socket.send('Hello Server!');
start_send();
});
window.srgt_socket.addEventListener('close', function (event) {
console.log('closing');
});
function start_send() {
var mediaConfig = { video: true };
var errBack = function(e) {
console.log('An error has occurred!', e)
};
// Put video listeners into place
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
/* Legacy code below! */
else if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(mediaConfig, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(mediaConfig, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
navigator.mozGetUserMedia(mediaConfig, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
setInterval(function(){
context.drawImage(video, 0, 0, 320, 100);
let canvas = document.getElementById('canvas');
let img = document.getElementById('img');
img.src = canvas.toDataURL("image/png");
let data = {
src : canvas.toDataURL("image/png"),
}
window.srgt_socket.send(JSON.stringify(data));
}, 33);
}
我使用websocket。在服务器端,我使用node.js.我不知道为什么连接会在一段时间后关闭(它工作几毫秒)。发送数据然后连接关闭。我是从localhost运行这个脚本的。