socket_write

(PHP 4 >= 4.1.0, PHP 5)

socket_writeЗапись в сокет

Описание

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

Функция socket_write() записывает в сокет socket данные из указанного буфера buffer.

Список параметров

socket

buffer

Буфер, который будет записан.

length

Необязательный параметр length может указывать другое число байт, записываемых в сокет. Если это число больше, чем длина буфера, оно будет молча урезано до длины буфера.

Возвращаемые значения

Возвращает количество байт, успешно записанных в сокет или FALSE в случае возникновения ошибки. Код ошибки может быть получен при помощи функции socket_last_error(). Этот код может быть передан функции socket_strerror() для получения текстового описания ошибки.

Замечание:

Совершенно нормально для функции socket_write() возвращать ноль, что означает, что ни одного байта не было записано. Пожалуйста, используйте оператор === для проверки значения на FALSE в случае ошибки.

Примечания

Замечание:

socket_write() не обязательно записывает все байты из указанного буфера. Нормально то, что, в зависимости от сетевых буферов и т. д., только некоторое количество данных, даже один байт, будет записан, хотя ваш буфер больше. Вы должны следить за тем, чтобы непреднамеренно не забыть передать остаток ваших данных.

Смотрите также

  • socket_accept() - Принимает соединение на сокете
  • socket_bind() - Привязывает имя к сокету
  • socket_connect() - Начинает соединение с сокетом
  • socket_listen() - Listens for a connection on a socket
  • socket_read() - Читает строку байт максимальной длины length из сокета
  • socket_strerror() - Возвращает строку, описывающую ошибку сокета

Коментарии

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.
2002-08-20 07:43:42
http://php5.kiev.ua/manual/ru/function.socket-write.html
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$linestrlen ($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 ;)
2006-08-23 13:27:23
http://php5.kiev.ua/manual/ru/function.socket-write.html
Hi,
if you got same problems like i have

<?php
@socket_write($xd"Good Bye!\n\r");
@
socket_shutdown($xd2);
@
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.
2008-08-26 14:42:03
http://php5.kiev.ua/manual/ru/function.socket-write.html
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;
        }
           
    }
?>
2010-12-20 19:08:08
http://php5.kiev.ua/manual/ru/function.socket-write.html
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;
    }
?>
2011-02-03 17:00:31
http://php5.kiev.ua/manual/ru/function.socket-write.html
function AddTCPChecksum(&$data){
//feel free to add some error handling for strlen($data)>65535...
$data=pack("v",strlen($data)).$data;
}
2015-02-06 19:14:15
http://php5.kiev.ua/manual/ru/function.socket-write.html
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] == || $matches] == ) return( $matches] );
        }
        else
        {
            return( 
false );
        }
    };
   
    try
    {
       
$socket null;
        if( ( 
$socket socket_createAF_INETSOCK_STREAMSOL_TCP ) ) == false )
        {
            throw new 
Exceptionsprintf"Unable to create a socket: %s"socket_strerrorsocket_last_error() ) ) );
        }
        if( !
socket_connect$socketMAIL_SERVERMAIL_PORT ) ) 
        {
            throw new 
Exceptionsprintf"Unable to connect to server %s: %s"MAIL_SERVERsocket_strerrorsocket_last_error() ) ) );
        }
       
$read socket_read$socket1024 );
        if( 
$read == false )
        {
            throw new 
Exceptionsprintf"Unable to read from socket: %s"socket_strerrorsocket_last_error() ) ) );
        }
       
        if( 
socket_write$socketsprintf"HELO %s\r\n"gethostname() ) ) === false )
        {
            throw new 
Exceptionsprintf"Unable to write to socket: %s"socket_strerrorsocket_last_error() ) ) );
        }
       
$read socket_read$socket1024 );
        if( 
$read == false )
        {
            throw new 
Exceptionsprintf"Unable to read from socket: %s"socket_strerrorsocket_last_error() ) ) );
        }
        else
        {
            if( ( 
$errCode $isError$read ) ) ) throw new Exception"Server responded with an error code $errCode);
        }
       
        if( 
socket_write$socketsprintf"MAIL FROM: %s\r\n"$from ) ) === false )
        {
            throw new 
Exceptionsprintf"Unable to write to socket: %s"socket_strerrorsocket_last_error() ) ) );
        }
       
$read socket_read$socket1024 );
        if( 
$read == false )
        {
            throw new 
Exceptionsprintf"Unable to read from socket: %s"socket_strerrorsocket_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 );
    }
}
2015-05-03 11:58:39
http://php5.kiev.ua/manual/ru/function.socket-write.html
Автор:
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";
}
2021-07-29 03:52:22
http://php5.kiev.ua/manual/ru/function.socket-write.html

    Поддержать сайт на родительском проекте КГБ