3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

51歳からのプログラミング 備忘 server send event(sse) - laravel 非同期通信

Last updated at Posted at 2019-06-28

非同期通信 なかなかできなかった。

とりあえず、出かける時間なので、コード。
後で備忘記録的に追加しよう。

チャットモドキは
https://qiita.com/old_cat/items/1a7a6a25619544247b56

client - side

index.blade.php
<script>
$(function(){
  var source = new EventSource('sse');
  source.onmessage = function(event){
         alert(event.data);
  }
});
</script>

route

route
route::get ('index',function(){return view('index');});
route::get ('sse', 'XController@sse');

controller

XController
class XController extends Controller{
      public function sse(){
             header('Content-Type: text/event-stream');
             header('Cache-Control: no-cache');

             echo "data:'test'\n\n";
             flush();
      }  
}

複数データの送受信

controller
$array = ['A'=>'a','B'=>'b','C'=>'c'];

header('Content-Type:text/event-stream');
echo 'data:'.json_encode($array);
echo "\n\n";
flush();
source = new EventSource('sse');
source.onmessage = function(d){
  var receive = JSON.parse(d.data);
  var A       = receive.A;
  var B       = receive.B;
}

二次元配列の取り出し

controller
$user = User::all()->toArray();
header('Content-Type:text/event-stream');
header('Cache-Control:no-cache);
echo "data:".json_encode($form);
echo "\n\n";
flush();
javascript
var source = new EventSource('sse');    //controller public function sse(){}
    source.onmessage = function(m){
           message   = JSON.parse(m.data);
           message.user.forEach(function(mess){
                   console.log(mess);
                   console.log(mess.user_name);
           }
     }

EventSource -property

サーバーからの情報は、message-eventで配信される。

プロパティ 使用例とか 説明的とか戻り値とか
onerror ev.onerror=function(){};
onmessage ev.onmessage=function(e){};
onopen ev.onopne=function(){}; connection was just opened
readyState 0-connectiong 1-open 2-close read-only
url source's Url read-only
withCredentials cross orgin set boolean

下記サイト様。
参考になりました。ありがとうございました。

https://developer.mozilla.org/ja/docs/Web/API/EventSource
https://qiita.com/okumurakengo/items/cbe6b3717b95944083a1
https://qiita.com/okumurakengo/items/cbe6b3717b95944083a1

3
2
1

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?