socket_write

(PHP 4 >= 4.1.0, PHP 5)

socket_writeEscreve em um socket

Descrição

int socket_write ( resource $socket , string $buffer [, int $length ] )
Aviso

Esta função é EXPERIMENTAL. O comportamento desta função, seu nome, incluindo toda documentação pode ser modificado sem aviso em futuras versões do PHP. Esta função deve ser usada por sua própria conta e risco.

A função socket_write() escreve em um socket socket de buffer.

O parâmetro opcional length pode especificar um comprimento alternativo de bytes escritos para o socket. Se esse comprimento é maior do que o comprimento do buffer, isso será silenciosamente truncado para o comprimento do buffer.

Retorna o número de bytes escritos com sucesso para o socket ou FALSE em um erro. O código de erro pode ser retornado com . Esse código deve ser passado para para pegar uma explicação textual do erro.

Nota:

socket_write() não necessariamente escreve todos os bytes dados do buffer. Isso é valido, dependendo da rede, buffers etc., somente uma quantidade segura de dados, sempre um byte, é escrito embora seu buffer seja maior. Você deve prestar atenção para involuntariamente esquecer de transmitir o restante dos seus dados.

Nota:

Isso é perfeitamente válido para socket_write() retornar zero que significa que não tem bytes para escrever. Tenha certeza de usar o operador === para checar por FALSE em caso de um erro.

Veja também , , , , e .

User Contributed Notes

jean at briskula dot si
Some clients (Flash's XMLSocket for example) won't fire a read event until a new line is recieved.

<?php
   
/*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
   
function write(&$sock,$msg) {
       
$msg = "$msg\n\0";
       
$length = strlen($msg);
        while(
true) {
           
$sent = socket_write($sock,$msg,$length);
            if(
$sent === false) {
                return
false;
            }
            if(
$sent < $length) {
               
$msg = substr($msg, $sent);
               
$length -= $sent;
                print(
"Message truncated: Resending: $msg");
            } else {
                return
true;
            }
        }
        return
false;
    }
?>
revelable at hotmail dot com
Here we have the same function to write a socket but with improved performance.

If the messager are not larger, they will be written entirely with a single socket_write() call. And is not needed to call the substr() function for the first bucle.

<?php
$st
="Message to sent";
$length = strlen($st);
       
    while (
true) {
       
       
$sent = socket_write($socket, $st, $length);
           
        if (
$sent === false) {
       
            break;
        }
           
       
// Check if the entire message has been sented
       
if ($sent < $length) {
               
           
// If not sent the entire message.
            // Get the part of the message that has not yet been sented as message
           
$st = substr($st, $sent);
               
           
// Get the length of the not sented part
           
$length -= $sent;

        } else {
           
            break;
        }
           
    }
?>
slyv at poczta dot onet dot pl
"socket_write() does not necessarily write all bytes from the given buffer."
So I wrote the following code to correctly write message to the socket

<?php
$message
="Message to sent";
$len = strlen($message);
$offset = 0;
while (
$offset < $len) {
   
$sent = socket_write($socket, substr($message, $offset), $len-$offset);
    if (
$sent === false) {
       
// Error occurred, break the while loop
       
break;
    }
   
$offset += $sent;
}
if (
$offset < $len) {
   
$errorcode = socket_last_error();
   
$errormsg = socket_strerror($errorcode);
    echo
"SENDING ERROR: $errormsg";
} else {
       
// Data sent ok
}
?>
masterwaster at gmail dot com
Hi,
if you got same problems like i have

<?php
@socket_write($xd, "Good Bye!\n\r");
@
socket_shutdown($xd, 2);
@
socket_close($xd);
?>

wont'tx send "Good Bye!\n\r" to the opened socket.

but if you put a
usleep or something like echo "";
between write and shutdown its working.
webmaster at you-are-infected dot com
If you connect to a Server in a way like you do with telnet or some similar protokoll you may have problems with sending data to the server. I found out that at some servers there is a different between:

<?php
   
    socket_write
($my_socket, $line, strlen ($line));
   
socket_write ($my_socket, "\r\n", strlen ("\r\n"));
   
?>
witch worked at least, and
<?php
    socket_write
($my_socket, $line."\r\n", strlen ($line."\r\n"));
?>
wich made the server stop sending any data.

I hope this helps to save a lot of time. I needed about two days to find out, that this was the problem ;)
gtk at linux dot online dot no
from
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.