Sunday, March 22, 2020

Laravel App Connect and Emit to Socket.io

Hello,

Recently in one of the project I was working on we have socket.io server created using NodeJS and there were couple of Angular applications and android applications connects with it. However there was a requirement to connect with socket from Laravel app and emit the event.

Actually there was a form in Laravel app on submit of Form we have to notify the socket and socket further notify all the clients connected to it. In this blog I am going to mention how we solved this.

We all know Laravel by default comes with integration of Pusher we could have used it. But since Socket.io is free so we consider to use Socket.io.

Let's go step by step and understand how to connect with Socket.io

Step 1

Create new folder socket in your app directory of Laravel app.

Step 2

Copy following class in to app/Socket folder and rename it to SocketIO.php

https://github.com/psinetron/PHP_SocketIO_Client

There are many PHP socket IO client is available but we used above one. You can choose either one of your choice.

Step 3

Connect and emit to socket. In your controller file where you want to emit the event. Add following code.

$socketIO = new SocketIO();
$returnValue = $socketIO->send('YOUR_URL', YOUR_PORT, 'YOUR_EVENT',json_encode(YOUR_PHP_ARRAY))

For this add following line to top of your controller.

use App\socket\SocketIO;

That's it and now you can connect with socket and emit event to it.

No comments:

Post a Comment