Home > Net >  Trying to tcp connect Laravel app to workerman server
Trying to tcp connect Laravel app to workerman server

Time:11-15

I have a server running and waiting/listening for connections. The server is based on Mark Framework which is using Workerman. So far I'm able to start the server and when I load the URL/host on the browser it shows content (in this case I'm expecting a simple Hello world).

This is index.php which I use to start the server

use Mark\App;
require 'vendor/autoload.php';

$api = new App('http://127.0.0.1:8080');
$api->count = 2; // process count

$api->any('/', function ($requst) {
    return 'Hello world';
});    

$api->start();

Now, I have a simple Laravel app that I want when I open a certain page to connect to that server and show the content from it.

I'm not sure how to do this. What I have so far in the controller is this

public function index() {

    try {

        $host = "127.0.0.1";
        $port = 8080;
        $resource =  stream_socket_client("tcp://$host:$port", $error_no, $error_str, 20, STREAM_CLIENT_CONNECT);

        $lines = stream_get_line($resource, 8192);
        
        var_dump($lines);

    } catch(Exception $e){
        return response($e->getMessage(), 500);
    }

    var_dump($resource);
    return View::make('index');
}

var_dump($resource) which is a variable for the connection shows

resource(10) of type (stream)

var_dump($lines); shows false which I guess is because the $resource doesn't make any connection

bool(false)

Any ideas here on how to approach this?

CodePudding user response:

TCP connection does not rely on any protocol, it's just a pure data transfer protocol which enables you to transfer bytes with ACL confirmation. You name it TCP and you include some Mark Framework which is http protocol based process.

The docs say it helps you to quickly write APIs with php. It means it's not a TCP raw server with custom protocol but it is a http protocol oriented server which is simply a REST API ready for http GET/POST requests to make your life easier.

You can do the same things with laravel on both sides until you need realtime connection. Realtime socket connections are made via javascript because HTTP is not built for this.

From laravel side just read: https://laravel.com/docs/9.x/http-client#making-requests

I might overwatched something, but sockets are rarely used in web. By calling TCP you called for 'sockets' and your post seems to negate your need for them.

  • Related