LoginSignup
6
6

More than 5 years have passed since last update.

Socket.ioを使ってサーバからクライアントに動画再生を制御する

Last updated at Posted at 2016-03-09

Socket.io

ネットワークで繋がった複数のタブレット(client)に対してPC(server)から動画再生の命令を出すテストをしてみた。
githubのexample/chatを参考にすると分かりやすい。chat app

structure

画像添付。無駄なファイルがあるけど気にしない。
Screen Shot 2016-03-09 at 22.09.11.png

run app

ターミナルでchatディレクトリに移動後、下記コマンドとたたく。

node server.js

code

html

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>frontapp/index.html</h1>
  <!-- put video for prototype -->
  <video id="video-player" width="640" height="480" controls>
    <source src="assets/test_movie.mp4" type="video/mp4">
  </video>
  <button id="client-trigger">push push here</button>

  <!-- need to import socketio.js -->
  <!-- also need to import main.js for front dev -->
  <script src="/socket.io/socket.io.js"></script>
  <script src="/frontapp.js"></script>
</body>
</html>

js

frontapp.js
(function(){

  var socket = io();
  setEventListener();

  // store video dom element in application
  var video = document.getElementById('video-player');
  // damn easy method to start play movie
  function playMovie(targetMovie) {
    targetMovie.play();
  }

  // set event listener
  function setEventListener() {
    document.getElementById('client-trigger').addEventListener("click", function(){
      video.play();
      console.log('hi there from client trigger');
    });
  }

  // listen socket
  socket.on('player trigger', function(data){
    //playMovie(video);
    video.play();
    console.log('hi there from server');
  });

})();
server.js
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 7000;

server.listen(port, function(){
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(__dirname + '/myapp'));

// connection established..
io.on('connection', function(socket) {
  var socketself = socket;
    setInterval(function() {
      console.log('7000 from server.js');
      // and send trigger
      socketself.broadcast.emit('player trigger', {
        trigger: 'triggervaluemaybe'
      });
    }, 5000);
});

problems

クライアント側で動画読み込みエラーが起きるとアプリが動かない。
読み込み出来てからサーバにemitさせるとすると、クライアント側もサーバにメッセージを送る必要があるかもしれない。

next

タブレットの再生する動画を次々に変えたい場合は、
1. サーバからクライアント端末に動画を転送する
2. クライアント端末がxhrを使ってバイナリデータを取得する
上記二つがぱっと思いつく。

再生トリガーを送る前の準備でまだいくつか調べないといけなそう。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6