Skip to content

Instantly share code, notes, and snippets.

@flushpot1125
Created May 18, 2025 06:40
Show Gist options
  • Select an option

  • Save flushpot1125/5863214f5d0fdd0c47f0ad4de66c0092 to your computer and use it in GitHub Desktop.

Select an option

Save flushpot1125/5863214f5d0fdd0c47f0ad4de66c0092 to your computer and use it in GitHub Desktop.
document.addEventListener('DOMContentLoaded', function() {
const img = document.getElementById('streamVideo');
const statusElem = document.getElementById('status');
// サーバーのWebSocketエンドポイントに接続
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/video`;
const ws = new WebSocket(wsUrl);
ws.onopen = function() {
statusElem.textContent = '接続完了 - 映像受信中';
};
ws.onmessage = function(message) {
// バイナリデータをBlobに変換
const blob = new Blob([message.data], { type: 'image/jpeg' });
// BlobからURLを作成し、img要素にセット
const url = URL.createObjectURL(blob);
img.src = url;
// メモリリークを防ぐために、古いURLを解放
img.onload = function() {
URL.revokeObjectURL(url);
};
};
ws.onclose = function() {
statusElem.textContent = '接続が閉じられました';
};
ws.onerror = function(error) {
statusElem.textContent = 'エラーが発生しました: ' + error.message;
console.error('WebSocket error:', error);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment