PHP gRPC Server & Nodejs Client

PHP gRPC Server & Nodejs Client

I'm gonna describe how easy to run PHP gRPC-server and code NodeJS gRPC- client

Hello friends, hope you are doing well!

I'm gonna describe how easy to run PHP gRPC-server and code NodeJS gRPC- client. At this article, I will highlight only the more important parts of setting up the workflow. You can find a done repository.

There will be considered a fast solution spiral/php-grpc to gRPC-server. Let's start off.

Firstly, look at docker-compose file:

version: '3.3'

services:

    grpc_php_server: # grpc server
        build:
            context: ./containers/php
            dockerfile: php.docker
        container_name: grpc_php_server
        working_dir: /app
        command: ./rr-grpc serve -v -d
        volumes:
            - ./src/php:/app

    grpc_php_protoc: # protoc generator 
        image:  grpc/php
        container_name: grpc_protoc
        working_dir: /app
        volumes:
            - ./src/php:/app

    client_nodejs: # grpc client
        image: node:latest
        container_name: client_nodejs
        command: node ./client.js
        working_dir: /app
        links:
          - grpc_php_server
        depends_on:
          - grpc_php_server
        volumes:
            - ./src/nodejs:/app

As you could see it's a very simple docker-compose file.

Note: if you want to play around, don't forget to grab all dependencies.

docker-compose run grpc_php_server composer install
docker-compose run client_nodejs npm install

The proto file was drawn up as very primitive way as I can 😏.

contrived.proto is for server and client:

syntax = "proto3";

package service;

service ContrivedService {
    rpc ContrivedMethod (ContrivedMessageRequest) returns (ContrivedMessageResponse) {
    }
}

message ContrivedMessageRequest {
    string body = 1;
}

message ContrivedMessageResponse {
    string body = 1;
}

That one was put at php/proto and nodejs/proto directories.

For generating needed interfaces and initiation skeleton for gRPC-server the following command was used:

docker-compose run grpc_php_protoc protoc --plugin=./protoc-gen-php-grpc --php_out=/app --php-grpc_out=/app ./proto/contrived.proto

The setting of grpc-server was hosted at root directory .rr.yaml:

grpc:
  listen: "tcp://:3000"
  proto: "./proto/contrived.proto"
  workers:
    command: "php worker.php"
    pool:
      numWorkers: 1
      maxJobs:    1

The worker.php can look like:

<?php
declare(strict_types=1);
/**
 * Sample GRPC PHP server.
 */
use Spiral\Goridge;
use Spiral\RoadRunner;
ini_set('display_errors', 'stderr');
require "vendor/autoload.php";
$server = new \Spiral\GRPC\Server();
$server->registerService(\Service\ContrivedServiceInterface::class, new \Service\ContrivedService());
$w = new RoadRunner\Worker(new Goridge\StreamRelay(STDIN, STDOUT));
$server->serve($w);

The ContrivedService.php can look like:

<?php
namespace Service;
use Service\ContrivedMessageRequest;
use Service\ContrivedMessageResponse;
use Service\ContrivedServiceInterface;
use Spiral\GRPC;
class ContrivedService implements ContrivedServiceInterface
{
    /**
     * @param GRPC\ContextInterface $ctx
     * @param ContrivedMessageRequest $in
     * @return ContrivedMessageResponse
     *
     * @throws GRPC\Exception\InvokeException
     */
    public function ContrivedMethod(GRPC\ContextInterface $ctx, ContrivedMessageRequest $in): ContrivedMessageResponse
    {
        $response = new ContrivedMessageResponse();
        $response->setBody("Hello");
        return $response;
    }
}

So, let's move up to js-client.

The client.js can look like:

const path = require('path');
const PROTO_PATH = path.resolve(__dirname, './proto/contrived.proto');
const GRPCClient = require('node-grpc-client');

const myClient = new GRPCClient(PROTO_PATH, 'service', 'ContrivedService', 'grpc_php_server:3000');

const dataToSend = {
    body: 'Nodejs client!'
};

myClient.runService('ContrivedMethod', dataToSend, (err, res) => {
    if (err) {
        console.error(err);
    }

    console.log('Service response\n', res);
});

For trying it out was used the following command:

 docker-compose up

The output result:

grpc_php_server    | DEBU[0000] [rpc]: started                               
grpc_php_server    | DEBU[0000] [grpc]: started                              
client_nodejs      | Service response
client_nodejs      |  { body: 'Hello' }

As you could see it's tremendous simple to start working with gRPC and start thinking of adapting that one to our workflow.

What kind of benefits of adopting GRPC:

  1. Easy to understand.
  2. Web infrastructure already built on top of HTTP.
  3. Great tooling for testing, inspection, and modification.
  4. Loose coupling between clients/server makes changes easy.
  5. High-quality HTTP implementations in every language.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Top Web Application Developer

Top Web Application Developer

You can also contact a web application development company for your business but then why not to contact the best web application development company that can turn up your business and customer satisfaction ratio to sky touching heights.

Not long-ago internet came into existence and the world has never been the same ever since. The Internet made sure that people and business do evolve at a faster rate than ever and was never merciful to the slow ones. Because of this competition and availability of any business with few clicks made India one of the hubs as IT center. This trend of constantly updating has given rise to smartphones, smart machines, wearable gadgets and a lot more is yet to come in the upcoming years. In such time it is always a good idea to hire Web App Developer from India at your service. They are expert in developing not only websites but web applications as well.

We at HireFullStackDeveloperIndia, have a huge team of experienced developers that have grasped over different domains in front and back end development. You can hire web app developers in India from us with many advantages that you won’t get anywhere else in the industry.

Here is why we are the best option if you are looking forward to hiring web app developers in India:

  • Flexible hiring models available, as per your convenience and requirement
  • Maximum ROI, compared to any other company or team of developers.
  • We provide you with Source code Authorization meaning code written for you belong only to you. It cannot be used or copied anywhere else.
  • All of our developers are sound with agile development methodology, so you will be in a constant loop of suggestions, ideas, trends, and updates about your project.
  • Our developers are good with creating custom web applications as well; it guarantees you a better product without any compromise of non-existing functionalities.
  • You can save huge costing on infrastructure by utilizing our hire web app developer in India program.
  • Your hired developer or team will be easily accessible to your preferred mode of communication.
  • You get to exercise complete control over your team or individual that you hire.
  • We believe in Integrity and Transparency.
  • Our developers are highly creative and motivated to deliver excellence.


HireFullStackDeveloperIndia is a Web Application Development Company in India that is known worldwide for our Innovative guaranteed solutions. You can inquire with us about your project and we will be providing you multiple suitable developers that are the best fit for your requirements. You can evaluate them and select one or multiple whosoever deems fit to you. After this, all you have to do is provide your valuable input to the resource through sprint base project development until you get delivery of your project.

Our engagement model will also allow you to get our development team to your site location and proceed with development from your premises.

Node.js vs PHP: Which is better for Backend Developer?

Node.js vs PHP: Which is better for Backend Developer?

PHP and Node.js are both powerful backends for dynamic websites. In this article, we will be talking about the key features & differences between Node.js and PHP, and also try to identify which technology is suitable for which purpose.

PHP and Node.js are both powerful backends for dynamic websites. They both fall under the same category, yet their features are quite distinct. There’s no doubt — PHP is the most known and commonly used language for server-side scripting. However, Node.js made it possible to use JavaScript programming on the server side when it was introduced in 2009, fueling the rise of sites with entirely JavaScript-powered stacks for front-end as well as back-end. Before Knowing their differences, let’s first see What’s the Node.js & Php.

PHP

PHP: Hypertext Preprocessor is a general-purpose programming language originally designed for web development. It was originally created by Rasmus Lerdorf in 1994, and ever since has been used as the first choice of language preference for content management systems like WordPress, Drupal and Joomla. As of the latest statistics of 2018, more than 80% of websites are built with PHP.

Node.js

Node.js is an open-source, cross-platform, JavaScript runtime environment, built on Chrome’s V8 JavaScript engine, that executes JavaScript code outside of a browser. It was created in 2009 and came up with the main advantage — Node.js allows to perform asynchronous programming. Although the percentage of websites that are built with Node.js is comparatively low (0,4%), it’s fastly becoming popular among developers.

Synchronous code executes line by line and proceeds to execute the next line of code when the current line has been executed.

Asynchronous code executes all the code at the same time.

Node.js vs PHP: Differences

Runtime environments :

While both JavaScript and PHP can be embedded directly into HTML, they both need an interpreter in order to run. PHP has long been readily straightforward to install and use on the server-side, and is powered by the Zend engine. Node.js is a runtime environment for JavaScript on the server side, powered by Google’s V8 JavaScript engine.

Simplicity :

PHP is conceptually much simpler to use than Node.js. When setting up a server, all you need is a “.php” file with some code wrapped between the tags, enter the URL into your browser, and you’re done. Behind the scenes, a web server like MySQL with PHP installed will be able to interpret the file and display your web page in your browser. Setting up a Node.js server, while not difficult, usually requires more lines of code, and a basic understanding of how closures and callback functions work.

Concurrency :

PHP is synchronous but there are some APIs that behave asynchronously apart from the synchronous lot. It uses multi-threaded blocking I/O to carry out multiple tasks to run parallels alongside each other.

Node.js is asynchronous in nature which means the JavaScript engine runs through the entire code in one go and does not wait for a function to return. It uses event-driven non blocking I/O execution model. The lines of code below the function will execute and the function be executing too and will return the output once done and thus it make Node.js fast.

Modules :

PHP uses module installing technologies like PEAR( framework and distribution system for reusable PHP components.)

Node.js comes bundled with a package management system called NPM (Node Package Manager).

Scalability:

PHP is supported across most popular content management systems (such as Drupal, Joomla, WordPress), which makes it an often choice as a tool for building blogs and e-commerce web applications. In contrast, Node.js efficiently serves as a tool for creating scalable dynamic solutions that deal with numerous I/O operations. It’s also possible to scale Node on multi-cores systems, though with more efforts.

Web Servers :

PHP runs on the Apache web server. It can also run on IIS web server in case of a windows machine. NPM does not need a web server, it runs on its own run time environment.

Performance :

Although Node.js is always highlighted as a high-performative one because of its asynchronous model, PHP has also evolved in this direction. With such libraries as ReactPHP, it has become possible for PHP to be used in event-driven programming as well.

However, when both the environments are compared, you will notice that Nodejs stands out to be a lot faster than PHP, due to following :-

Speed Friendly V8 Engine

Continued Server connection

Callback functions which process many requests at the same time

When Should You Use PHP or Node.js?

Both are back-end technologies, but Node.js can offer an advantage if you’re looking to have a totally JavaScript technology stack across both the front and back ends. If you’re trying to choose between back-end technologies or are building an entire solution stack, it helps to go into a little more detail.

When to use PHP :-

Centralized Server : In case we do not plan on scaling our application across multiple servers we can use LAMP (Linux, Apache, MySQL and PHP) stack. This might change depending on project requirements and growth.

Portability: PHP is a highly portable language. The cheap costs of web hosting and the availability of the servers for PHP is comparable to none. PHP can run on almost any platform that has Apache, IIS and a supported database system installed, this makes PHP applications portable and easy to deploy.

When to use Node.js:-

Same Language across the Stack : Node.js will be the correct choice to use if your project involves software stacks such as MEAN stack ( MongoDB, ExpressJs, AngularJs.), dynamic single page applications, server side technologies and Front end technologies like Angular Js, Backbone.Js or React Js. This makes it easier to have the same language (Javascript) across your whole stack.

Realtime Data: Node.js is great for applications that require real time data, however I would be skeptical about using Node.js for financial applications as Javascript itself is not reliable when it comes to numbers as everything is integer or float and not much separation is done between the types. A more type safe language is recommended when working on financial applications that require lot of computing or a library that is reliable enough.

Speed: Node.js is much faster than PHP when it comes to execution speed, if speed is what you require for your application, such as a browser based multiplayer game or a chat application, Node.js is a great choice than PHP.

Conclusion

Although discussions around Node.js vs PHP don’t seem to cease any soon, the important thing to remember is that there’s nothing unique that you can do only with one of them — they are interchangeable. However, you can always orient at the level of development expertise and stack of technologies that are to be used in the process of development.

Thank you for reading this article, Hope it helps :)