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

socket_set_option

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

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

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

function.socket-set-option.php

socket_set_option

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

socket_set_optionПоставува опции на сокетот за сокетот

= NULL

socket_set_option(
         Сокет $socket,
         int $level,
         int $option,
         array|string|int $value
): bool

На socket_set_option() функцијата поставува опција специфицирана од option параметарот, на специфицираниот протокол levelдо вредноста посочена од value параметарот за socket.

Параметри

socket

А Сокет инстанца креирана со socket_create() or socket_accept().

level

На level параметарот специфицира ниво на протокол на кое се наоѓа опцијата. На пример, за поставување опции на ниво на сокет, level параметарот SOL_SOCKET би се користел. Други нивоа, како што е TCP, може да се користат со специфицирање на бројот на протоколот на тоа ниво. Броевите на протоколи може да се најдат со користење на getprotobyname() function.

option

Достапните опции на сокетот се исти како оние за socket_get_option() function.

value

Вредноста на опцијата.

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

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

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

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

Примери

Пример #1 socket_set_option() example

<?php
$socket
= socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!
is_resource($socket)) {
echo
'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo
'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!
socket_bind($socket, '127.0.0.1', 1223)) {
echo
'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

$rval = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR);

if (
$rval === false) {
echo
'Unable to get socket option: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else if (
$rval !== 0) {
echo
'SO_REUSEADDR is set on socket !' . PHP_EOL;
}
?>

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

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

drenintell
20 години пред
To expand a bit more on what "tim at e2-media dot co dot nz" started.

SO_SNDTIMEO is one of the many constants you can use with socket_set_option.

See http://ca.php.net/manual/en/ref.sockets.php for the available Predefind Constants and visit http://man.he.net/man2/setsockopt for the meaning of the ones relevant.

Tim's example might seem at first a bit non-intuitive since he is using the SO_SNDTIMEO constant. Which means, if the socket has to send out data, it must do it within the limit specified - in his case 10 seconds. Usually you won't set a timeout for sending out data. Nevertheless, the example is valid, and there are situations where you need to do so.

A more intuitive use of socket_set_option would be to set a time out for a blocking socket (a socket that waits for data to be receive when read from). You would do this like so:

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>0, "usec"=>100));

Notice that sec= 0 and usec= 100; Depending on how long you want your program to wait to recieve data, you might want to change these values.

Regards,
  drenintell
aeolian meson at ifacfchi dot blitzeclipse dot com
пред 17 години
Lingering will sometimes not work when you're working with non-blocking sockets. Even if the socket is set to linger and you keep tying to close until the socket doesn't return an error and the resource is no longer identifiable as type 'Socket', the socket may STILL close without sending everything.

Therefore, in the event that you are using non-blocking sockets (which is preferable if you care at all about signaling), you should set the socket as blocking (socket_set_block()) before calling to close it. This will allow everything to flush before it returns.

Dustin Oprea
gmail корисник asmqb7
пред 6 години
PLEASE NOTE

PHP 7.3.6, and probably many previous versions, automatically sets SO_REUSEADDR when you use stream_socket_server().

php_network_bind_socket_to_local_addr() is called at https://github.com/php/php-src/blob/623911f993f39ebbe75abe2771fc89faf6b15b9b/main/streams/xp_socket.c#L675 and defined at https://github.com/php/php-src/blob/61a6a6ec51297506c54f3c6e60ace9b892d0a3e4/main/network.c#L401 and if you take a look you'll see

#ifdef SO_REUSEADDR
            setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&sockoptval, sizeof(sockoptval));
#endif

I initially thought I'd need to play with context options to turn this on, but no, the simplest single-arg call with no error checking and just an address, works for me.

strace your PHP binary to be 100% sure:

...
setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
...

The chances are you ARE using SO_REUSEADDR unless you're using a 100-year old UNIX clone in a month with a Z in it.
renmengyang567 na gmail dot com
пред 6 години
<question>
 Why is the size of the buffer 2 times that set by me?
<?php
//Before setting the cache area
$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_bind($sock, '127.0.0.1',5000);
socket_listen($sock,1024);
$sndbuf = socket_get_option($sock,SOL_SOCKET,SO_SNDBUF);
$rcvbuf = socket_get_option($sock,SOL_SOCKET,SO_RCVBUF);
printf("send buffer size(写缓存区大小):%sm \n",$sndbuf/1024);
printf("receive buffer(读缓存区大小)%sm \n",$rcvbuf/1024);

//After setting the cache area
$snd_buf = 1024*3;
$rcv_buf = 1024*3;

socket_set_option($sock,SOL_SOCKET,SO_SNDBUF, $snd_buf);
socket_set_option($sock,SOL_SOCKET,SO_RCVBUF, $rcv_buf);
$sndbuf = socket_get_option($sock,SOL_SOCKET,SO_SNDBUF);
$rcvbuf = socket_get_option($sock,SOL_SOCKET,SO_RCVBUF);

printf("send buffer size(写缓存区大小):%sm \n",$sndbuf/1024);
printf("receive buffer size(读缓存区大小)%sm \n",$rcvbuf/1024);
?>
ludvig dot ericson на gmail dot com
19 години пред
I would like to comment on the previous note regarding blocking sockets.
There is more to blocking sockets than waiting for data to be received when trying to be read upon, just to make example, a listening blocking socket will wait for a client to try to connect before it returns when you socket_accept() it.
tim на e2-media dot co dot nz
21 години пред
To set a socket timeout value (assuming you've set it blocking) use:

socket_set_option(
  $socket,
  SOL_SOCKET,  // socket level
  SO_SNDTIMEO, // timeout option
  array(
    "sec"=>10, // Timeout in seconds
    "usec"=>0  // I assume timeout in microseconds
    )
  );
DaveRandom
пред 15 години
Setting the socket timeout microseconds ('usec') does not work under Windows, at least under PHP/5.2.9:

<?php

  $timeout = array('sec'=>1,'usec'=>500000);
  socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,$timeout);
  var_dump(socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO));

?>

Output on Windows box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(0)
}

Output on Linux box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(500000)
}
ckozler на kozler dot net
пред 14 години
It appears that Winsock does not acknowledge timeout (send and receive) on Windows.
На оваа страница

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

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

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

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

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