PHP 5.6.0RC3 is available

socket_write

(PHP 4 >= 4.1.0, PHP 5)

socket_writeEscribir en un socket

Descripción

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

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 6 notes

up
1
gtk at linux dot online dot no
11 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
masterwaster at gmail dot com
5 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
1
revelable at hotmail dot com
3 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
0
Anonymous
4 days ago
Watch out for these examples and contributions.

First off, in the official examples you must confirm that socket_write() has written your data, and in most cases that it has written all your data, as the example is usually a "write one thing and then finish" case where the socket is not left open.

I am pretty sure you cannot keep calling socket_write() on data that you already called it upon just because it has not been sent in the first call to socket_write(). If buffering ever occurs, you would end up re-sending fragments of your data.

You should not use a sleep/wait to compensate for the fact that output is buffered.

And finally, you should not be confused as to why separating your data into two separate calls to socket_write() results in receiving data on the far end, and yet one call does not.

All of these problems with the contributed examples show a lack of understanding of Buffering.
up
0
webmaster at you-are-infected dot com
7 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
-3
jean at briskula dot si
3 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;
    }
?>
To Top