Question about Socket php

0

I'm starting to study about Sockets, and I took as base the code from the following video: link

The question is: Why does it only work when calling through the cls in CMD? When I start the apache service in Xampp, and I try to run the servers through the browser, it does not work.

I have already done the netstat -a, -an command to get a port that is not being used.

I am using the following codes: Customer:

<?php
echo "\n Type your username:  ";
$user = trim(fgets(STDIN));
if(strlen($user) <= 2) { exit; }
else {
while(1)
{   
    echo "\n Please say something or enter 'q' to quit:  ";
    $ticker = trim(fgets(STDIN));
    if($ticker=='q') { exit; }

    $socket= socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
    if($socket===false)
    {
        echo "Socket creation failed!";
    }
    $result = socket_connect($socket,"127.0.0.1",1234);
    if($result===false)
    {
        echo "Socket connection failed!";
    }
        else { 
        socket_write($socket,"$user says --> $ticker",1024);
         }
    }
}
?>

Server:

<?php
error_reporting(0);
set_time_limit(0);
$host = "127.0.0.1";
$port = 1234;
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create
socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to
socket\n");
$result = socket_listen($socket) or die("Could not set up socket
listener\n");
echo "Waiting for connections... \n";
while(1)
{
    $spawn[++$i] = socket_accept($socket) or die("Could not accept incoming
    connection\n");
    echo "_______________________________________________________\n";
    $input = socket_read($spawn[$i],1024);
    $client = $input;

    echo $client ."\n";

    socket_close($spawn[$i]);
    echo "_______________________________________________________\n";
}
socket_close($socket);
?>

Ps: Even through CMD, if I start apache in Xampp it does not work.

If someone can send a client / server code just so I can study, how it works in the browser, it would help me a lot. Thanks!

    
asked by anonymous 12.05.2017 / 17:23

1 answer

0

You should test if the extension is compiled before using the sockets:

if (!extension_loaded('sockets')) {
    die('Sockets não disponível.');
}

It is probably only present in the CLI version.

    
12.05.2017 / 17:45