使用laravel创建简单的websocket应用

2018-02-08 01:54:22   php分享记录

 

首先使用composer安装cboden/ratchet类包以及相关依赖

  1. composer require cboden/ratchet

然后,创建WebsocketController控制器

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Facades\Log;
  4. use Ratchet\ConnectionInterface;
  5. use Ratchet\MessageComponentInterface;
  6. class WebsocketController extends Controller implements MessageComponentInterface
  7. {
  8. protected $clients;
  9. public function __construct()
  10. {
  11. $this->clients = new \SplObjectStorage();
  12. }
  13. public function onOpen(ConnectionInterface $conn) {
  14. //存储连接的websocket链接,用于待会返回消息
  15. $this->clients->attach($conn);
  16. }
  17. public function onMessage(ConnectionInterface $from, $msg) {
  18. foreach ($this->clients as $client){
  19. if($from != $client){
  20. //发送消息给所有连接的客户端(除开发送者)
  21. $client->send($msg);
  22. }
  23. }
  24. }
  25. public function onClose(ConnectionInterface $conn) {
  26. $this->clients->detach($conn);
  27. }
  28. public function onError(ConnectionInterface $conn, \Exception $e) {
  29. $conn->close();
  30. }
  31. }

控制器创建完成后,使用laravel的命令行命令创建command

  1. php artisan make:console websocket laravel:websocket

该语句会在app\console\commands目录下创建websocket.php文件

修改websocket.php

  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Http\Controllers\WebsocketController;
  4. use Illuminate\Console\Command;
  5. class Websocket extends Command
  6. {
  7. /**
  8. * The name and signature of the console command.
  9. *
  10. * @var string
  11. */
  12. protected $signature = 'laravel:websocket';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = 'Command description';
  19. /**
  20. * Create a new command instance.
  21. *
  22. * @return void
  23. */
  24. protected $app;
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. //
  29. $app = new \Ratchet\App('192.168.31.66', 2345,'0.0.0.0');
  30. $app->route('/chat', new WebsocketController(), array('*'));
  31. // $app->route('/echo', new \Ratchet\Server\EchoServer, array('*'));
  32. $app->run();
  33. }
  34. public function handle()
  35. {
  36. echo "success!!";
  37. }
  38. }

命令创建完成后,在laravel目录根目录位置打开控制台,输入

  1. php artisan laravel:websocket

就会开启一个独立的后台程序运行该程序

最后,前台连接websoket

  1. var conn = new WebSocket('ws://192.168.31.66:2345/chat');
  2. conn.onopen = function (ev) {
  3. console.log('已连接');
  4. };
  5. conn.onerror = function(){
  6. setTimeout(connected,2000);
  7. };
  8. conn.onmessage = function(){
  9. };

至此,一个简单的websocket应用就实现了,可以实现简单的全屏通知