Git Product home page Git Product logo

codeigniter-websocket's Introduction

Latest Version on Packagist Total Downloads

takielias

CodeIgniter WebSocket Library

CodeIgniter WebSocket library. It allows you to make powerfull realtime applications by using Ratchet (Socketo.me & ratchet_client) Websocket technology.

WebSocket Library for Codeigniter 4.x https://github.com/takielias/codeigniter4-websocket

If you Face any problem you may check CodeIgniter WebSocket Example https://github.com/takielias/codeigniter-websocket-example

📚 Dependencies

  • PHP 5.6+
  • CodeIgniter Framework (3.1.* recommanded)
  • Composer
  • PHP sockets extension enabled

🔰 Installation

➡️ Step 1 : Library installation by Composer

Just by running following command in the folder of your project :

composer require takielias/codeigniter-websocket

Don't forget to include your autoload to CI config file :

$config['composer_autoload'] = FCPATH.'vendor/autoload.php';

➡️ Step 2 : One command Setup

If you want Single command installation just Execute the Command in the Project directory

N.B: It will make 2 new controllers Welcome.php and User.php

php vendor/takielias/codeigniter-websocket/install.php --app_path=application

Here app_path defines your default Codeigniter Application directory Name

one click installation

WOW You made it !!! ✔️

Open two pages of your project on following url with different IDs :

http://localhost/your project directory/index.php/user/index/1

http://localhost/your project directory/index.php/user/index/2

❗ In this example, recipient_id is defined by user_id, as you can see, it's the auth callback who defines recipient ids.

If you have something like that, everything is ok for you:

user_1

user_2

You can try typing and sending something in each page (see cmd for more logs).

cmd

➡️ Run the Websocket server Manually

If you want to enable debug mode type the command bellow in you'r project folder :

php index.php welcome index

If you see the message the message bellow, you are done (don't close your cmd) !

First_launch.png

➡️ Test the App

Broadcast messages with your php App 💥 !

If you want to broadcast message with php script or something else you can use library like textalk/websocket (who is included in my composer.json as required library)

Note : The first message is mandatory and always here to perform authentication

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

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

Authentication & callbacks ♻️

The library allow you to define some callbacks, here's an example :

class Welcome extends CI_Controller
{
    public function index()
    {
        // Load package path
        $this->load->add_package_path(FCPATH . 'vendor/takielias/codeigniter-websocket');
        $this->load->library('Codeigniter_websocket');
        $this->load->remove_package_path(FCPATH . 'vendor/takielias/codeigniter-websocket');

        // Run server
        $this->codeigniter_websocket->set_callback('auth', array($this, '_auth'));
        $this->codeigniter_websocket->set_callback('event', array($this, '_event'));
        $this->codeigniter_websocket->run();
    }

    public function _auth($datas = null)
    {
        // Here you can verify everything you want to perform user login.
        // However, method must return integer (client ID) if auth succedeed and false if not.
        return (!empty($datas->user_id)) ? $datas->user_id : false;
    }

    public function _event($datas = null)
    {
        // Here you can do everyting you want, each time message is received
        echo 'Hey ! I\'m an EVENT callback'.PHP_EOL;
    }
}
  • Auth type callback is called at first message posted from client.
  • Event type callback is called on every message posted.

How to receive response into Codeigniter Controller ?

Please look at the Welcome.php controller.

public function index()
{
	// Load package path
	$this->load->add_package_path(FCPATH . 'vendor/takielias/codeigniter-websocket');
	$this->load->library('Codeigniter_websocket');
	$this->load->remove_package_path(FCPATH . 'vendor/takielias/codeigniter-websocket');

	// Run server
	$this->codeigniter_websocket->set_callback('auth', array($this, '_auth'));
	$this->codeigniter_websocket->set_callback('event', array($this, '_event'));
	$this->codeigniter_websocket->set_callback('roomleave', array($this, '_roomleave'));
	$this->codeigniter_websocket->run();
}

public function _roomleave($data = null)
{
	// Here you will receive data from the frontend roomleave event trigger.
	echo 'Hey ! I\'m a room leave EVENT callback' . PHP_EOL;
}

The main concept is the callback function.

You would receive the response into the defined function. You can trigger the event from the front end like below using jQuery

    socket.send(JSON.stringify({
        'type': 'roomleave',
        'room_name': targetName,
        'user_id': "buzz4rd"
    }));

It would trigger the function below

public function _roomleave($data = null)
{
	// Here you will receive data from fron tend roomleave event trigger.
	echo 'Hey ! I\'m a room leave EVENT callback' . PHP_EOL;
}

You May Check Room Chat using PHP websocket. It was built using this

Bugs 🐛 or feature 💪

Be free to open an issue or send pull request

Support on Buy Me A Coffee

Hey dude! Help me out for a cup of ☕!

takielias

codeigniter-websocket's People

Contributors

takielias avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

codeigniter-websocket's Issues

should we change websocket connection url on real host?

when we upload to real server , should we change connection code? it's working now but sometimes it crash . and somtimes i get this error

WebSocket connection to 'ws://localhost:8282/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

should we change this part of code on real host?

 var conn = new WebSocket('ws://localhost:8282');

'Ratchet\MessageComponentInterface' not found

I install the project example and it works fine
but when i install the library to an existing project by using this command
php vendor/takielias/codeigniter-websocket/install.php --app_path=application
i get this Error. i update composer and same error i got

Severity: Error
Message: Interface 'Ratchet\MessageComponentInterface' not found
Filename: C:\xampp\htdocs\shareweight\vendor\takielias\codeigniter-websocket
libraries\Codeigniter_websocket.php
Line Number: 186

Error using the client class for sending message to users

I get this error when i call the client class to send message to users connected on the socket

$client = new Client('ws://127.0.0.1:8080');
$client->send(json_encode(array('user_id' => 1, 'message' => null)));
$client->send(json_encode(array('user_id' => 1, 'message' => 'Super cool message to myself!')));

Here is the error:
An error has occurred: Connection to 'ws://127.0.0.1/' failed: Server sent invalid upgrade response:

Error: Object not found!

http://localhost/websocket/user/index/1
it shows me this!! i think the problem is from code igniter it self !

Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

If you think this is a server error, please contact the webmaster.

Error 404
localhost
Apache/2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.4

Error call controller, can you help me?

My source code has config Route and remove index.php and using sql server.
When run 'php index.php welcome index ', it show error:
`C:\xampp\htdocs>php index.php welcome index

An uncaught Exception was encountered

Type: Error
Message: Call to undefined function sqlsrv_connect()
Filename: C:\xampp\htdocs\system\database\drivers\sqlsrv\sqlsrv_driver.php
Line Number: 144

Backtrace:
File: C:\xampp\htdocs\application\controllers\Load_Page.php
Line: 8
Function: __construct

    File: C:\xampp\htdocs\index.php
    Line: 315
    Function: require_once`

My source code working ok.
image
image
image
image

Cannot connect to web socket

I have run the web socket as shown in the command below:

$ php index.php test index
Running server on host 0.0.0.0:8282
Authentication activated

However, when I tried on the client side, I am getting the console message as:
WS connection attempt ${4-ctx.tryCount} -> Unsuccessful

Please kindly assist. Thanks in advance.

PS: I edit the view to show if it is connected or not. Below is the code.

var wsFactory = { tryCount: 3,
    connect : function(url){
        var ctx = this,
            ws  = new WebSocket(url);

        return new Promise(function(v,x){
            ws.onerror   = e => { console.log('WS connection attempt ${4-ctx.tryCount} -> Unsuccessful');
                e.target.readyState === 3 && --ctx.tryCount;
                if (ctx.tryCount > 0) setTimeout(() => v(ctx.connect(url)), 1000);
            else x(new Error("3 unsuccessfull connection attempts"));
            };
            ws.onopen    = e => {
                console.log('WS connection Status: ${e.target.readyState}');
                console.log("here: "+client.user_id);
                conn.send(JSON.stringify(client));
                $('#messages').append('<font color="green">Successfully connected as user ' + client.user_id + '</font><br>');
                v(ws);
            };
            ws.onmessage = m => {
                console.log(m.data);
                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);
                }
            };
        });
    }
};

wsFactory.connect("ws://blablabla.com:8282")
    .then(ws => ws.send("Hey..! This is my first socket message"))
.catch(console.log);

Server will not run after running manual command

I followed the tutorial, and it worked very well, but after I completed step 2, I closed the server via ctrl+c and tried the manual command "php index.php welcome index". I receive this error as a response:
An uncaught Exception was encountered

Type: WebSocket\ConnectionException
Message: Could not open socket to "0.0.0.0:8282": Connection refused (111).
Filename: /opt/lampp/htdocs/codeigniter/vendor/textalk/websocket/lib/Client.php
Line Number: 95

Backtrace:
File: /opt/lampp/htdocs/codeigniter/vendor/textalk/websocket/lib/Base.php
Line: 48
Function: connect

File: /opt/lampp/htdocs/codeigniter/application/models/Classic_firearms.php
Line: 25
Function: send

File: /opt/lampp/htdocs/codeigniter/index.php
Line: 315
Function: require_once

If I try to run "php vendor/takielias/codeigniter-websocket/install.php --app_path=application" again, the server starts and immediately closes and returns back to the command line. Did I do something wrong?

user_id receiving same message when user_id and recipient_id is the same

I really appreciation your great work. Your work has really helped a lot.
Thus, an issue occurred if a particular user is the initiator of the chat, the user would be able to send message out but would also be the receiver of that same message provided that the user_id and recipient_id are both the same. However, if both user_id and recipient_id differs, the code works fine.
The problem now is to be able to differentiate user_id from recipient_id even if they both have same id value.
Thank you!

croperror

https http wss ws

Hi friend, I'm having problems using it in https. Can you help me?

What happens is that I can't start it with https, so I can't use wss to connect the client to the service.

Do you have any idea how to solve this?
Captura de tela de 2022-06-13 21-13-43

Group chat?

Is it possible to make it work with multiple recipients? Like a group chat.

How can I send commands from the server to the client directly?

I tried to use this code to send messages to the client:

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

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

And I have used this line to import the library:

use WebSocket\Client;

This is giving me this error:

Socket Error 10049 - The specified address is not available from the local computer

¿How can I solve this?

running server manually on macos (apple silicon)

How to running server on macos with apple silicon?

i'm running on terminal with command "php index.php welcome index" return html code like this
Jepretan Layar 2023-01-15 pukul 21 38 20

but i try on windows it's running smoothly. Anyone can help?

Is there any way to restart the WebSocket server?

Hi everybody!

I searched the method to stop the websocket server but i did not found.

I need this to disable some services on my server when it is in high load. But I need that my Apache keep working. (restart Apache is out of case).

This library is awesome. Congratulations for it

How to use with HTTPS?

i used your example with my live server and i found that with https its fails to connect.

i tried to find some solution over google but not work.
i found 1 solution for this to add .crt and .pem file in ratchet function parameter but i don't no how to add that files in this library
i have this both file but don't no how to pass this 2 files in parameter

i am using shared hosting

Not sending message via php

Hi there,

I've changed the php text to "ws://localhost:8282" as having it as 0.0.0.0 was giving a 10049 error (where as localhost doesn't give any error).

Still it seems to not be working correctly. If I connect via javascript it seems to be working fine, but when I send a message using php I don't get anything.

PHP (not working)
`public function test_webs(){
$socket_client = new WebSocket\Client("ws://0.0.0.0:8282");

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

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

conn.onopen = function (e) {
    conn.send(JSON.stringify(client));
    console.log("Socket open");
};

conn.onmessage = function (e) {
    var data = JSON.parse(e.data);
    if (data.message) {

        console.log("Incomming User "+data.user_id+": ");
        console.log(data.message);
    }
    if (data.type === 'token') {
        // $('#token').html('JWT Token : ' + data.token);
        console.log('JWT Token : ' + data.token);
    }
};`

Assistance will be appreciated.

Stuck in connection phase when app is deployed to AWS.

So I got this library to work in localhost, but I can't seem to get it to work on my AWS Lightsail instance. I did everything in the readme, but no dice.
I changed the WebSocket in welcome_message.php to have the IP of my server
var conn = new WebSocket('ws://555.555.555.5:8282');//fake ip for security

And I wrapped conn.send in in a try and catch block to to see if I could catch anything:

$('#submit').click(function () {
        client.message = $('#text').val();
        client.token = $('#token').text().split(': ')[1];
        client.type = 'chat';
        if ($('#recipient_id').val()) {
            client.recipient_id = $('#recipient_id').val();
        }
        try {
            conn.send(JSON.stringify(client));
        } catch (error) {
            console.log(error);
        }
    });

The Try/catch block throws this error:
DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
It seems to always be stuck in the connection phase. Do I need to open up a port or something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.