vendredi 28 février 2020

How to implement Websockets on Codeigniter?

I need to send progress notifications on a process' state during the process in my Codeigniter app. I asked my professors, and they said the best solution is Websockets. I found a great library for websockets in codeigniter here, and it does work, but I can't seem to figure out how to send messages from the model to a view.

I did the simple setup with the "php vendor/takielias/codeigniter-websocket/install.php --app_path=application" command, and I was able to have to 2 'clients' talk to one another in real time. I was even able to get one of them to talk to my view php file.

Now I just need to get the model to talk to the view. I tried adding this to the top of the model file:

defined('BASEPATH') OR exit('No direct script access allowed');
require('vendor/autoload.php');

use WebSocket\Client;

And then I try to log in in the modal's constructor with this:

            $this->client = new Client('ws://0.0.0.0:8282');

            $this->client->send(json_encode(array('user_id' => 1, 'message' => null)));
            $this->client->send(json_encode(array('user_id' => 1, 'message' => 'Super cool message to myself!')));

The readme states that the first message is necessary for validation of the connection.

Despite this, I never receive the message on the view file. The socket code in my view is:

var conn = new WebSocket('ws://localhost:8282');
var client = {
    user_id: 1,
    recipient_id: null,
    type: 'socket',
    token: null,
    message: null
};

conn.onopen = function (e) {
    conn.send(JSON.stringify(client));
    $('#messages').append('<font color="green">Successfully connected as user ' + client.user_id + '</font><br>');
};

conn.onmessage = function (e) {
    var data = JSON.parse(e.data);
    if (data.message) {
        $('#messages').append(data.user_id + ' : ' + data.message + '<br>');
    }
    if (data.type === 'token') {
        $('#token').html('JWT Token : ' + data.token);
    }
};

Let me guess, its the ports? I played around with them to no avail. Any ideas?




Aucun commentaire:

Enregistrer un commentaire