Laravel Websockets, some gotchas!

There is a really nice websocket composer package for laravel but a couple of issues that you may hit along the way! So the package is by beyondcode and it is here. A really nice package, but here are some gotchas that I came across.

  1. 403 Forbidden error on the auth URL
  2. 401 Unauthorized error on the auth URL
  3. Using namespaces within the listen to Echo method

So, the first 2 are kinder within the manual but I didn’t read it and in turn came up with the issues!. So going to split the 3 issues into separate areas below

403 Forbidden error on the auth URL

When you aren’t using the websocket locally, then you may hit request error of 403 and this is because of the gate defined within the Beyondcode class WebSocketsServiceProvider and method called registerDashboardGate

protected function registerDashboardGate() { Gate::define(‘viewWebSocketsDashboard’, function ($user = null) { return app()->environment(‘local’); });

and this as you can tell, is checking if the current application is running within the “local” environment setting and hence why you didn’t notice it whilst testing locally, the problem is within the config/websockets.php file

‘middleware’ =>

[ ‘web’, Authorize::class, ],

where the Authorize::class is the beyondcode class calling the above method, so we just need to replace with our authorization middleware e.g. jwt.auth.

401 Unauthorized error on the auth URL

The next issue I noticed was an error similar to

$key cannot obtain from null

This is because of the AuthenticateDashboard method that has

$app = App::findById($request->header(‘x-app-id’));
$broadcaster = new PusherBroadcaster(new Pusher( $app->key,

This is because the x-app-id wasn’t being passed in within the auth request, so altering the laravel Echo javascript object creation to include the following key value pair (please note I change the websockets.php path configuration to “websockets”

window.Echo = new Echo({ …….

authorizer : (channel, options) => {
return {
authorize: (socketId, callback) => {
axios.post(‘/websockets/auth’, {
socket_id : socketId,
channel_name: channel.name,
},
{ headers: { ‘x-app-id’: ‘<your ID from within the websockets.php configuration file, normally this is apps>’ } })
.then((response) => {
// error report
callback(false, response.data)
})
.catch((error) => {
// error report
callback(true, error)
// throw new Error(error)
})
},
}
},

Using namespaces within the listen to Echo method

The last part was the namespace issue within the echo listen to the method, where I don’t want to define the namespace of the broadcast every time like (where the App.Events was the namespace within php)

window.Echo.private(`dashboard.${dashboardID}’) .listen(‘App.Events.DashboardUpdate’, (e) => { e.message.value.forEach(function (value) { vm.$set(vm.data, value.key, value.value) }) })

So, like the above fix, we just need to add an option to the new Echo object within the javascript

window.Echo = new Echo({ …….

namespace : ‘App.Events’,

Those were the things that caused me to think, so thought it may be a good idea to post about it encase anyone else has the same issue, if you need more information on each please say!

Morse code

As a test, I was asked to write a morse code task where some of the signals weren’t able to be determined from the input. So in this case instead of having either the dot (.) or dash (-) we have a question mark (?) where it could be either a dot / dash.

Here is an image of the morse code alphabet of dots / dashes and here is a link to a view of the “tree” of the morse code of the dichotomic search, basically binary search of the morse code.

So, we are only going down 3 levels, below are some tests to confirm that the process is working fine.

  • .- = A
  • . = E
  • … = S
  • -.- = K
  • ? = ET
  • -? = NM

So, I approached this test by thinking that I need to have an “item” that stores the current value (e.g. character) and left / right item, and here is my item.h definition.

class item {
    private:
        char value;
        item *left;
        item *right;
    public:
        item(char value,item *left,item *right);
        item(char value);
        item(item *left,item *right);

        item();

        char getValue();

        item* leftItem();
        item* rightItem();
};

And then to build the 3 levels of the search tree

    item* head = new item(
        new item('e',
            new item('i', 
                new item('s'),
                new item('u')
            ),
            new item('a',
                new item('r'),
                new item('w')
            )
        ),
        new item('t',
            new item('n', 
                new item('d'),
                new item('k')
            ),
            new item('m',
                new item('g'),
                new item('o')
            )
        )
    );

and then the last part was literally reading in the signal to be processed and going down the tree either left / right or both for undermined signal.

string output(string signal, item* codes) {
    string ret="";
    if (signal.size() ==0 ) 
        return string(1,codes->getValue());
    for (string::size_type i=0; i < signal.size();i++) {
        if ('?' == signal[i]) {
            ret += output("."+signal.substr(i+1),codes);
            ret += output("-"+signal.substr(i+1),codes);
            return ret;
        } else if ('.' == signal[i]) {
            return output(signal.substr(i+1),codes->leftItem());
        } else if ('-' == signal[i]) {
            return output(signal.substr(i+1),codes->rightItem());
        } else {
            throw invalid_argument(string("Invalid character at this point of the string ").append(signal));
        }
    }
    return ret;
}

If you want to view the whole code, here is the link to the zip file of the morse code.

php 7 – generator – yield’s

php 7 has now implement generators where you are able to return (yield) results from a method and only the ones that you will need.

// define the output as type Generator -- e.g. yield results.. the compiler will still work without this Generator keyword
function yieldSomeNumbers() : Generator {  
    yield 10;
    yield 13;
}
 
foreach (yieldSomeNumbers() as $v) {
    var_dump($v);
}

Will output

10
13

The ‘Generator’ at the end of the method ” : Generator” is not actual needed as the compiler will append it as such on the fly since the method is yield results.

For example, lets say that you are doing a search of numbers from 1-100 and are searching for the value of 10, so before generators the code would have been something like

function generateNumbers() {
    return range(1,100);   // load up a array of values 1-100 e.g. 1,2,3,4,5...
}
 
foreach (generateNumbers() as $v){
    var_dump($v);
    if ($v == 10) {
        var_dump("FOUND");
        break;
    }
}

The ‘foreach (generateNumbers()’ will be using the full array where as

function generateSomeNumbers() : Generator {
    foreach (range(1,100) as $v) {
        yield $v;
    }
}
 
foreach (generateSomeNumbers() as $v){
    var_dump($v);
    if ($v == 10) {
        var_dump("FOUND");
        break;
    }
}

will only return each yield upon request.

php 7 – strict typing and return types

This is going to be the first of my PHP 7 posts where PHP 7 has grown up and has PHP 7 taken a massive leap forwards!!!

So the first thing is return types, before PHP 7 there was no return typing e.g.

function add($a,$b) {
    return $a + $b;
}
 
echo add("hi there","good");

was a “valid” PHP code!!

But now with not only parameter type hinting, you are also able to use return types with strict typing as well!. So to start with, this is defining the return type of int (just before the function body there is the :int)

function add(int $a,int $b): int {
    return (int)($a + $b);
}
 
echo add(2,3);

The answer of course will be 5, but you could still be silly and allow PHP to convert string characters (that was alphanumeric) to integers, for example calling the above function like

echo add("2","3");

Would still work and give the answer of 5!, which is kinder wrong!.

So there is the strict typing which enforces the correct parameter being used.

So if you change the above code to

declare(strict_types=1);
 
 
function add(int $a,int $b): int {
    return (int)($a + $b);
}
 
 
var_dump(add(2,3));
var_dump(add("2","3"));
exit;

The output would be

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given, called in /home/genux/Programming/php7/scalar.php on line 12 and def
ined in /home/genux/Programming/php7/scalar.php:5
Stack trace:
#0 /home/genux/Programming/php7/scalar.php(12): add('2', '3')
#1 {main}
  thrown in /home/genux/Programming/php7/scalar.php on line 5

Which means that you have pass in the integer values, as in strict typing and not just assume PHP will be “cool” and just sort it out for you.

Await and async

I was working on an project that was using the async and await keywords and an college asked what/why use the await/ async keywords when you will still be waiting on the task / thread to finish. Which was an very good question, and the best answer that I could give (of which I am writing it here) is that if you want to start an thread and let it process it’s work whilst still carrying on with the main thread then you would need to write some thread controls etc. But .Net gives you that thread control with the async / await keywords.

The async is short for asynchronous which basically means do something whilst doing something else, e.g. you are able to talk and listen at the same time!.

So what happens is that you can create an method to do some long processing, I am just using an Task delay here to simulate that with also using the await syntax just before it so that it will actually wait for the task delay to finish, as below

 public async Task<Boolean> getCheckAsync(Boolean c)
        {
            System.Console.WriteLine("getCheckAsync about to wait");
            await Task.Delay(1000);
            System.Console.WriteLine("getCheckAsync finished waiting");
            // do some processing.. pulling data from a database / website etc.
            if (c)
                return false;
            else
                return true;
        }

You have to decorate the method call with async Task, since then you will be able to do some await on this method.

The next part is to create an call to this method, and this will start the call as well — start processing the method of getCheckAsync

 Task<Boolean> getCheckAsyncTask = this.getCheckAsync(t);            // calls the process to start processing -- e.g. will output "getCheckAsync about to wait"

And to await for the result, which means that you are able to do some other actions in between the calling the method (getCheckAsync) and waiting on the result.

Boolean res = await getCheckAsyncTask;

So from the full code example below, the first output would be

Calling the async
Waiting for result from getCheckAsync
getCheckAsync about to wait
Bit inbetween the getCheckAsync call

which as you can see has already called the getCheckAsync method and then carried on processing the bit inbetween that is not reliant on the result of the method call (getCheckAsync), but once we are ready for the result of the getCheckAsync method call, the output would carry on with

getCheckAsync finished waiting
Obtainted the result from getCheckAsync
Passed the 'Calling the async'
B = False

Here is the code in full

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace asynctest
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
 
            System.Console.WriteLine("Calling the async ");
 
            Boolean b = p.getCheck(true).Result; 
 
            System.Console.WriteLine("Passed the 'Calling the async'");
            System.Console.WriteLine("B = "+b);
            System.Console.ReadLine();
        }
 
        public async Task<Boolean> getCheck(Boolean t)
        {
            System.Console.WriteLine("Waiting for result from getCheckAsync ");
            Task<Boolean> getCheckAsyncTask = this.getCheckAsync(t);            // calls the process to start processing -- e.g. will output "getCheckAsync about to wait"
            System.Console.WriteLine("Bit inbetween the getCheckAsync call");   // do some extra processing.
            Boolean res = await getCheckAsyncTask;                              // but now we have to "await" for the result.
            System.Console.WriteLine("Obtainted the result from getCheckAsync ");
            return res;
        }
 
        public async Task<Boolean> getCheckAsync(Boolean c)
        {
            System.Console.WriteLine("getCheckAsync about to wait");
            await Task.Delay(1000);
            System.Console.WriteLine("getCheckAsync finished waiting");
            // do some processing.. pulling data from a database / website etc.
            if (c)
                return false;
            else
                return true;
        }
 
    }
}

vectors and for_each

A friend of mine asked how to use the newer for_each and is it similar to the foreach in php, so here is the example that I gave and thus doing it online as well.

To start with the foreach (php version here) does loop over data and so does the for_each in c++, but the main difference is that the for_each in c++ is basically a for loop

for (; first!=last;++first)
   functionCall(*first);

where the functionCall is the parameter passed in to do something with that part of the data.

The great thing with c++ is that you are able to use either a method, structure etc as long as it is able to output a variable then we are good.

So here is a example, please note that I am loading up a vector e.g. only functions that have a single int make sense.

void printNumber (int i) {
	cout << "Print the number from a function : " << i << "\n";
}
 
for_each(v.begin(), v.end(), printNumber);

here we are using the for_each (where the v is a vector) passing in the start and end of the vector with a function as the last parameter.

and here

// create a object that can use the operator() to output value passed in.
struct structToOutput {
	void operator() (int i) {
		cout << "Struct to output : " << i << "\n";
	}
} structToOutputObject;
 
for_each(v.begin(), v.end(), structToOutputObject);

will output the values differently but in essence still able to access the values.

Here is the code in full

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
void printNumber (int i) {
	cout << "Print the number from a function : " << i << "\n";
}
 
// create a object that can use the operator() to output value passed in.
struct structToOutput {
	void operator() (int i) {
		cout << "Struct to output : " << i << "\n";
	}
} structToOutputObject;
 
int main(int argc, char* argv[])
{
	// lets load up some dummy data.
	vector<int> v;
	for (int i =0; i< 10; i++)
		v.push_back(i);
 
	// run through the vector using a standard function with parameter
	for_each(v.begin(), v.end(), printNumber);
	// output using a operator() method
	for_each(v.begin(), v.end(), structToOutputObject);
	return 0;
}

with the output being

Print the number from a function : 0
Print the number from a function : 1
Print the number from a function : 2
Print the number from a function : 3
Print the number from a function : 4
Print the number from a function : 5
Print the number from a function : 6
Print the number from a function : 7
Print the number from a function : 8
Print the number from a function : 9
Struct to output : 0
Struct to output : 1
Struct to output : 2
Struct to output : 3
Struct to output : 4
Struct to output : 5
Struct to output : 6
Struct to output : 7
Struct to output : 8
Struct to output : 9

How to compile with g++

g++ <filename> -o <outfilename> -std=c++11

auto and lambda

The C++ 11 standards are starting to take more and more cue’s from other languages where you are able to create functions on the fly (lambda). With also adding the “auto” keyword which will allow the program to automatically figure out what type of variable will be returned from lambda function.

So here the break up of the lambda function is

<return type> <[optional local variables to be used]>(optional parameters);

The optional local variables are abit like the “use” within PHP (use)

So the full code is

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main(int argc, char* argv[])
{
	int num = 30;
	int anothernum = 0;
 
	auto func = [&anothernum](int i) {
			cout << "Parameter passed in :" << i << "\n";
			anothernum = anothernum + 10; // alter the value passed in.
			return 50;	// return a value and use the auto keyword.
	};
	int ret = func(num);
	cout << "Return from func :" << ret << "\n";
	cout << "Another num :" << anothernum << "\n";
	return 0;
}

and the output would be

Parameter passed in : 30
Return from func : 50
Another num : 10;

To compile with g++ I used these parameters

g++ <filename> -o <outfilename> -std=c++11