LoginSignup
9

More than 5 years have passed since last update.

socket.io-php-emitter で PHP から emit する方法

Last updated at Posted at 2016-09-16

動かすには Redis と PHP の Redis ライブラリが必要です。

使用したバージョン

  • PHP 7.0.10
  • Redis 3.2.3
  • Node.js 4.3.2
  • npm 2.14.12

サンプルソース

server/package.json

{
  "name": "sample-server",
  "main": "index.js",
  "dependencies": {
    "express": "^4.10.2",
    "socket.io": "^1.4.8",
    "socket.io-redis": "^1.0.0"
  },
  "devDependencies": {
    "nodemon": "^1.9.1"
  }
}

server/index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var redis = require('socket.io-redis');
var adapter = io.adapter(redis({ host: '127.0.0.1', port: 6379 }));

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

server/index.html

<script src="https://cdn.socket.io/socket.io-1.4.8.js"></script>
<script>
  var socket = io.connect('http://localhost:3000/');

  socket.on('update', function(socket){
    console.log('received emit!');
  });
</script>

php-emitter/composer.json

{
    "name": "sample-client",
    "type": "project",
    "require": {
        "ashiina/socket.io-emitter": "^0.8.0"
    }
}

2016年09月16日現在、rase/socket.io-emitter には互換性の問題があり動作しないため、代わりに有志の方が公開した修正版の ashiina/socket.io-emitter を使用しています。詳細は socket.io-php-emitter 0.7.0が動作しない問題 の記事を参照してください。

php-emitter/src/client.php

<?php
require_once('../vendor/autoload.php');

$redis = new \Redis();
$redis->connect('127.0.0.1', '6379');

$emitter = new SocketIO\Emitter($redis);
$emitter->emit('update', 'data'));

確認方法

以下のコマンドで node サーバを起動した状態で、ブラウザで index.html (http://localhost:3000/) を表示しておきます。

node index.js 

その状態で client.php を実行してコンソールに received emit! と表示されれば疎通成功です。🎉

疎通確認時のデバッグに便利な方法

最初試したときに中々繋がらなくて苦労したので、役に立ったデバッグ方法を書いておきます。

1. サーバのデバッグモードの有効化

デバッグモードを有効にして node サーバを起動しておくと emit 時に詳細な情報が流れます。

DEBUG=* node index.js

2. Redis のモニタリング

Redis を介して emit するため、Redis のコンソールで monitor コマンドを実行しておくと実際の通信内容 (msgpack) の文字列を確認できます。

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
9