MartinZeltin
7 months ago
1464
2
Laravel

How to use Websockets without echo and laravel-websockets

Posted 7 months ago by MartinZeltin

I am trying to implement websockets in my Laravel application. I tried to use the beyondcode/laravel-websockets PHP package with Laravel Echo but it was too difficult and complicated. When I tried to broadcast an event it didn't work.

So I turned to Node.js and with native HTTP ws API. It is very simple to use but I can't use it from inside of my Laravel application to broadcast a message. I want to keep it very simple, what are my options?

Here is how I set it up using Node.js (very simple)

Node.js

const WebSocket = require('ws')
const server = new WebSocket.Server({ port: 6001 })

server.on('connection', ws => {
    setInterval(() => {
        ws.send('Random data: ' + Math.random())
    }, 2000)
})

client/index.html

<script>
    const connection = new WebSocket(`ws://${window.location.hostname}:6001`)

    connection.addEventListener('message', event => {
        console.log(event.data)
    })
</script>

It works but how can I integrate it into Laravel? Without making it too complicated.

Please sign in or create an account to participate in this conversation.