socket_write

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_writeEscribir en un socket

Descripción

socket_write(resource $socket, string $buffer, int $length = 0): int

La función socket_write() escribe en el socket desde el buffer dado.

Parámetros

socket

buffer

El buffer a ser escrito.

length

El parámetro opcional length puede especificar una longitud alternativa de bytes escritos en el socket. Si esta longitud es mayor que la longitud del buffer se trunca de forma silenciosa a la longitud del buffer.

Valores devueltos

Devuelve el número de bytes escritos con éxito en el socket o false en caso de error. El código de error se puede recuperar con socket_last_error(). Este código se puede pasar a socket_strerror() para obtener una explicación textual del error.

Nota:

Es perfectamente válido que socket_write() devuelva cero, lo que significa que no se han escrito bytes. Asegúrese de usar el operador === para verificar false en caso de un error.

Notas

Nota:

socket_write() no escribe necesariamente todos los bytes desde el buffer dado. Esto es válido ya que depende de los búferes de red, etc., sólo se escribe una cierta cantidad de informaicón, incluso un byte, aunque su buffer sea mayor. Debe tener cuidado de no olvidar inintencionadamente de transmitir el resto de la información.

Ver también

add a note add a note

User Contributed Notes 8 notes

up
9
revelable at hotmail dot com
13 years ago
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;
        }
           
    }
?>
up
1
php at deguest dot asia
9 years ago
I often read in php docs users not checking for the php function returned value, and in the case of socket_write, I could not see here in the comment anyone botering to read on the socket the server reply.
Then one user thought it would be a good idea to use usleep after a socket_write on a smtp connection.
Actually, if you check the server reply, not only will it give time for the server to reply before you write again on the socket, but also this is a great opportunity to check what the server replied you.
For instance, for smtp connection :
In this example MAIL_SERVER, MAIL_PORT and DEBUG are constants I defined.
<?php
function sendmail( $param )
{
   
$from    = &$param[ 'from' ];
   
$to      = &$param[ 'to' ];
   
$message = &$param[ 'data' ];
   
   
$isError = function( $string )
    {
        if(
preg_match( '/^((\d)(\d{2}))/', $string, $matches ) )
        {
            if(
$matches[ 2 ] == 4 || $matches[ 2 ] == 5 ) return( $matches[ 1 ] );
        }
        else
        {
            return(
false );
        }
    };
   
    try
    {
       
$socket = null;
        if( (
$socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ) ) == false )
        {
            throw new
Exception( sprintf( "Unable to create a socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        if( !
socket_connect( $socket, MAIL_SERVER, MAIL_PORT ) )
        {
            throw new
Exception( sprintf( "Unable to connect to server %s: %s", MAIL_SERVER, socket_strerror( socket_last_error() ) ) );
        }
       
$read = socket_read( $socket, 1024 );
        if(
$read == false )
        {
            throw new
Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
        }
       
        if(
socket_write( $socket, sprintf( "HELO %s\r\n", gethostname() ) ) === false )
        {
            throw new
Exception( sprintf( "Unable to write to socket: %s", socket_strerror( socket_last_error() ) ) );
        }
       
$read = socket_read( $socket, 1024 );
        if(
$read == false )
        {
            throw new
Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        else
        {
            if( (
$errCode = $isError( $read ) ) ) throw new Exception( "Server responded with an error code $errCode" );
        }
       
        if(
socket_write( $socket, sprintf( "MAIL FROM: %s\r\n", $from ) ) === false )
        {
            throw new
Exception( sprintf( "Unable to write to socket: %s", socket_strerror( socket_last_error() ) ) );
        }
       
$read = socket_read( $socket, 1024 );
        if(
$read == false )
        {
            throw new
Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        else
        {
            if( (
$errCode = $isError( $read ) ) ) throw new Exception( "Server responded with an error code $errCode" );
        }
       
/* And some more code, but not enough place in comment */
       
return( $totalWriten );
    }
    catch(
Exception $e )
    {
       
$ERROR = sprintf( "Error sending mail message at line %d. ", $e->getLine() ) . $e->getMessage();
        return(
false );
    }
}
up
1
gtk at linux dot online dot no
22 years ago
from http://www.manualy.sk/sock-faq/unix-socket-faq-2.html
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.
up
1
anonymous
3 years ago
sending a few mbs or more results in incomplete transfers, send data in a loop and chunks instead, socket_write reports complete write even though it is only a partial transfer, possibly because of buffer overrun somewhere.

$strlen=strlen($msg);
$totaltransferred=0;

$blocksize=10000;
for ($a=0;$a<$strlen;$a+=$blocksize){
    $part=substr($msg,$a,$blocksize);
    $transferred=socket_write($socket,$part,strlen($part));
    $totaltransferred+=$transferred;
}
   
if ($totaltransferred<$strlen){
    echo "incomplete transfer";
}
up
-2
webmaster at you-are-infected dot com
18 years ago
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 ;)
up
-5
jean at briskula dot si
13 years ago
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;
    }
?>
up
-7
masterwaster at gmail dot com
16 years ago
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.
up
-7
divinity76 at gmail dot com
9 years ago
function AddTCPChecksum(&$data){
//feel free to add some error handling for strlen($data)>65535...
$data=pack("v",strlen($data)).$data;
}
To Top