Laravel-swoole: WebSocket events not firing.

Created on 8 Jun 2018  路  11Comments  路  Source: swooletw/laravel-swoole

Please answer these questions before submitting your issue. Thanks!

  1. Please provide your PHP and Swoole version. (php -v and php --ri swoole)

PHP

PHP 7.2.6 (cli) (built: May 25 2018 06:18:43) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.6, Copyright (c) 1999-2018, by Zend Technologies

Swoole

swoole

swoole support => enabled
Version => 2.2.0
Author => tianfeng.han[email: [email protected]]
coroutine => enabled
kqueue => enabled
rwlock => enabled
async http/websocket client => enabled
sockets => enabled
pcre => enabled
zlib => enabled

Directive => Local Value => Master Value
swoole.aio_thread_num => 2 => 2
swoole.display_errors => On => On
swoole.use_namespace => On => On
swoole.use_shortname => On => On
swoole.fast_serialize => Off => Off
swoole.unixsock_buffer_size => 8388608 => 8388608
  1. Please provide your Laravel/Lumen version.
Lumen (5.5.2) (Laravel Components 5.5.*)
  1. Which release version of this package are you using?
"swooletw/laravel-swoole": "^2.3",
  1. What did you do? If possible, provide a recipe for reproducing the error.

I created a websocket server using swooletw/laravel-swoole and connected it with Socket.io client.
Everythings looks fine. The WebSocket was connected. however, On the socket server the Connect and Open events not firing. Only disconnect event is working.

Here is my websocket.php routes.

<?php

use Illuminate\Http\Request;
use SwooleTW\Http\Websocket\Facades\Websocket;

/*
|--------------------------------------------------------------------------
| Websocket Routes
|--------------------------------------------------------------------------
|
| Here is where you can register websocket events for your application.
|
*/
Websocket::on('open', function ($websocket, $request) {
    Log::info('Opened' . $websocket->getSender());
});

Websocket::on('connect', function ($websocket, $request) {
    Log::info('Connected' . $websocket->getSender());
    // called while socket on connect.
});

Websocket::on('disconnect', function ($websocket) {
    Log::info('Disconnected' . $websocket->getSender());
    // called while socket on disconnect
});

And here is my frontend code.

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
    <script type="text/javascript">
        const socket = io.connect('http://127.0.0.1:1215')

        socket.on('connect', () => console.log(socket.id))
        socket.on('disconnect', reason => console.log(reason))

        setTimeout(() => {
            socket.emit('messages')
        }, 100)
        socket.on('messages', m => {
            document.querySelector('#messages').innerText = m
            // console.log(JSON.parse(base64Decode(m)))
        })

        const base64Decode = (str) => {
            return decodeURIComponent(atob(str).split('').map(function(c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
            }).join(''))
        }

Here is my logs.

[2018-06-08 03:50:19] lumen.INFO: Disconnected2  
[2018-06-08 03:50:21] lumen.INFO: Disconnected5  
[2018-06-08 03:50:21] lumen.INFO: Disconnected7  
[2018-06-08 03:50:21] lumen.INFO: Disconnected8  
[2018-06-08 03:50:21] lumen.INFO: Disconnected9  

I'm sorry for my poor English.

question

Most helpful comment

I an find error.

const ws = io.connect('http://127.0.0.1:1215');

// replaced by

const ws = io('http://127.0.0.1:1215', {transports: ['websocket']});

All 11 comments

Hi @damonto ,

Thanks for willing to open an issue in English. It makes all the discussions in this community more friendly to the people from all over the world.

Please check your web console if the websocket connection is established. It looks like your connection is refused by the server. You can use this online client to test if you can connect to your websocket server.

@albertcht Thank you for your suggestion. I will try it on the next working day and report the results.

All events are working on the Socket.io Client Tool. Maybe it's my front-end code problem.

snipaste_2018-06-12_22-08-24
When I use the online client to connect server with Lumen 5.6
snipaste_2018-06-12_22-16-16

Hi @dickwu ,

Do you enable your websocket server correctly? Type php artisan swoole:http infos to check if you turn websocket mode on. And you just need to enter 127.0.0.1:1215 for your host in the client tool.

snipaste_2018-06-13_10-37-38

url changed but still Websocket init failed
snipaste_2018-06-13_10-46-02

@albertcht

Hi @dickwu ,

Tested with a fresh Lumen (5.6.3) repo, it worked fine. See lumen-swoole-demo for reference. If it only happens in your project, that means somewhere in your code changed this behavior. And please open another new issue for that with more detailed information, thanks.

Hello. Sorry for my bad English. This problem actuality for me.
The project has just been deployed. It's clean.

+-----------------+---------------------------------------------------------------------+
| Name            | Value                                                               |
+-----------------+---------------------------------------------------------------------+
| PHP Version     | 7.2.4                                                               |
| Swoole Version  | 4.0.1                                                               |
| Laravel Version | 5.6.26                                                              |
| Listen IP       | 127.0.0.1                                                           |
| Listen Port     | 1215                                                                |
| Server Status   | Offline                                                             |
| Reactor Num     | 4                                                                   |
| Worker Num      | 4                                                                   |
| Task Worker Num | 4                                                                   |
| Websocket Mode  | On                                                                  |
| PID             | None                                                                |
| Log Path        | /Users/rkovjogin/Work/php/tomono-chats/storage/logs/swoole_http.log |
+-----------------+---------------------------------------------------------------------+

I am use this routes;

Websocket::on('open', function ($websocket, $request) {
    Log::info('open');
});

Websocket::on('connect', function ($websocket, Request $request) {
    Log::info('connect');
});

```javascript

// That's how it works. Event was work in Laravel
const server = new WebSocket('ws://127.0.0.1:1215');

   server.onopen = function (evt) {
        console.log("Connected to WebSocket server."); // work
    };

    server.onmessage = function (event) {
        console.log(event); // { ..., data: "42["event","welcome"]", origin: "ws://127.0.0.1:1215", ...}
    }


```javascript
// if i am use soket.io. JS works. Laravel events "open" and "connected" do not work. The rest - work (disconnected, test and any).
        const ws = io.connect('http://127.0.0.1:1215');
        ws.on('connected', () => {
            console.log('connected'); // It was displayed in the console, but the event did not hit Laravel
        });

        ws.on('event', (data) => {
            console.log('event', data); // I called this event in the lab. The inscription in the console appeared.
        })

I an find error.

const ws = io.connect('http://127.0.0.1:1215');

// replaced by

const ws = io('http://127.0.0.1:1215', {transports: ['websocket']});

Where to write this code in laravel while my route is http://127.0.0.1:9501/socket.io

const server = new WebSocket('ws://127.0.0.1:1215');

   server.onopen = function (evt) {
        console.log("Connected to WebSocket server."); // work
    };

    server.onmessage = function (event) {
        console.log(event); // { ..., data: "42["event","welcome"]", origin: "ws://127.0.0.1:1215", ...}
    }

@Sravan2 , please open a new issue about your question, and I highly suggest you can learn some basic knowledge about websocket and socket.io before you open an issue.

You need to interact with the websocket server with a socket.io client, or you can choose to implement your own websocket handler and connect it with native WebSocket client.

Was this page helpful?
0 / 5 - 0 ratings