PHP with sockets

Asked

Viewed 1,447 times

1

How do I use PHP with socket? Can be any type...
I need to create notifications and a chat.

I’ve tried many ways, but I can never. :/

  • Can you ask the question one of the ways you tried? It will be easier to identify what your difficulty is. Have you studied the documentation? What was in doubt and what didn’t work?

  • Good evening. Could you improve the details of the question? Generally, when speaking of socket in PHP, you may be referring to the command line. Or do you want to chat via HTML? If this is the second case, you can use Websocket.

  • Yes, I wish to use the second case (HTML). But I’m not getting it done. :/

1 answer

1


Simple TCP/IP server

This example shows a simple exchange of server information. Change the address and port variables for the set of your configuration and execution. You must then connect the server with a command line similar to: telnet 192.168.1.53 10000 (where the address and port originate from your configuration). Something you type will then exit on the server side, and show it to you. To disconnect, type 'quit'.

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Permite que o script fique por aí esperando conexões. */
set_time_limit(0);

/* Ativa o fluxo de saída implícito para ver o que estamos recebendo à medida que ele vem. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() falhou: razao: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() falhou: razao: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() falhou: razao: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() falhou: razao: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Envia instruções. */
    $msg = "\nBem-vindo ao PHP Test Server. \n" .
        "Para sair, digite 'quit'. Para desligar digite 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() falhou: razao: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: Você disse: '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>

Simple TCP/IP client

This example shows a simple, one-shot HTTP client. This simply connects to a page, sends a request header, shows the answer, and exits.

<?php
error_reporting(E_ALL);

echo "<h2>Conexão TCP/IP</h2>\n";

/* Obtem a porta para o serviço WWW. */
$service_port = getservbyname('www', 'tcp');

/* Obtem o endereço IP para o host alvo. */
$address = gethostbyname('www.example.com');

/* Cria o socket TCP/IP  */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() falhou: razao: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Tentando se conectar a '$address' na porta '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() falhou.\nRazao: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Conexão: Fechar\r\n\r\n";
$out = '';

echo "Enviando solicitação HEAD HTTP...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Resposta de leitura:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

echo "Fechando socket...";
socket_close($socket);
echo "OK.\n\n";
?>

Read more about sockets:

Documentation - SOCKETS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.