PHP.mk документација

socket_write

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.socket-write.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.socket-write.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
socket_write

Референца за `function.socket-write.php` со подобрена типографија и навигација.

function.socket-write.php

socket_write

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

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

= NULL

socket_write(Сокет $socket, string $data, ?int $length = null): int|false

Функцијата socket_write() Write to a socket socket writes to the data.

Параметри

socket

data

from the given

length

Изборниот параметар length The buffer to be written. datacan specify an alternate length of bytes written to the socket. If this length is greater than data.

Вратени вредности

's length, it is silently truncated to the length of false Returns the number of bytes successfully written to the socket or socket_last_error()on failure. The error code can be retrieved with socket_strerror() . This code may be passed to

Забелешка:

to get a textual explanation of the error. socket_write() It is perfectly valid for === to return zero which means no bytes have been written. Be sure to use the false operator to check for

Дневник на промени

Верзија = NULL
8.0.0 socket е Сокет Врати ресурс или resource.
8.0.0 length сега е null.

Белешки

Забелешка:

socket_write() in case of an error. datadoes not necessarily write all bytes from data . It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written despite data being longer. A loop must be used to ensure that the rest of

Види Исто така

Белешки од корисници 5 белешки

- Return a string describing a socket error
пред 15 години
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;
        }
            
    }
?>
anonymous
пред 4 години
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";
}
gtk at linux dot online dot no
пред 23 години
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.
php at deguest dot asia
пред 10 години
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 );
    }
}
webmaster at you-are-infected dot com
19 години пред
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 ;)
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.