PHP-Fusion
v.7.01
AP-Fusion
v7.02.04
Pimped-Fusion-AP
v0.09.03
мая 25 2012 12:05:00
Навигация
· Новости
· Статьи
· Скачать
· Форум
· Ссылки
· Категории новостей
· Обратная связь
· Галерея
· Поиск
· Гостевая
· Коллекция аватар
· CMS AP-Fusion. Отличия от PHP-Fusion
· Javascript справочник
· Разное
· Техника
Сейчас на сайте
· Гостей: 3

· Пользователей: 0

· Всего пользователей: 445
· Новый пользователь: vesuvius
Информеры
Загрузка файлов  +  -
Бытовая техника:  +  
Лента alipapa.ru
Карпаты. Верховина.
Карпаты. Драгобрат.
Карпаты. Яремче, Яблунецкий перевал.
dbForge Studio for MySQL вместо PHPMyAdmin
Облачные технологии - насколько это серьезно?
Как распределяется вес по сайту

Совместимость CMS
Solomono.ru - сервис для веб-мастера
Микроразметка веб-страниц.
АГС - не приговор.

Немного о политике.
Что такое АГС и как с ним бороться?
Долгожданный АП PR

PR Google: 9 месяцев без апдейта
Поведенческий фактор - модная тенденция?
Wi-Fi дома. Что делать, если 192.168.0.1 занято?

Ускоренная переиндексация страниц в Яндексе
Как я ставил винду на нетбук.
ROOKEE - инструмент оптимизатора.
Строим рейтинг-каталог
Ссылки  +  -
Блоги
Alipapa
» Блог Алипапы
lom
» Блог Лома

socket_create_pair

(PHP 4 >= 4.1.0, PHP 5)

socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in an array

Description

bool socket_create_pair ( int domain, int type, int protocol, array &fd )

socket_create_pair() creates two connected and indistinguishable sockets, and stores them in fd. This function is commonly used in IPC (InterProcess Communication).

The domain parameter specifies the protocol family to be used by the socket.

Таблица 1. Available address/protocol families

DomainDescription
AF_INETIPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family. Supported only in windows.
AF_INET6IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family. Support added in PHP 5.0.0. Supported only in windows.
AF_UNIXLocal communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).

The type parameter selects the type of communication to be used by the socket.

Таблица 2. Available socket types

TypeDescription
SOCK_STREAMProvides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
SOCK_DGRAMSupports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.
SOCK_SEQPACKETProvides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.
SOCK_RAWProvides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping, traceroute, etc).
SOCK_RDMProvides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

Таблица 3. Common protocols

NameDescription
icmpThe Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.
udpThe User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.
tcpThe Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

Пример 1. socket_create_pair() example

<?php
$sockets
= array();
$uniqid = uniqid ( '' );
if (
file_exists ( "/tmp/$uniqid.sock" )) {
    die(
'Temporary socket already exists.' );
}
/* Setup socket pair */
if (! socket_create_pair ( AF_UNIX , SOCK_STREAM , 0 , $sockets )) {
    echo
socket_strerror ( socket_last_error ());
}
/* Send and Recieve Data */
if (! socket_write ( $sockets [ 0 ], "ABCdef123\n" , strlen ( "ABCdef123\n" ))) {
    echo
socket_strerror ( socket_last_error ());
}
if (!
$data = socket_read ( $sockets [ 1 ], strlen ( "ABCdef123\n" ), PHP_BINARY_READ )) {
    echo
socket_strerror ( socket_last_error ());
}
var_dump ( $data );

/* Close sockets */
socket_close ( $sockets [ 0 ]);
socket_close ( $sockets [ 1 ]);
?>

Пример 2. socket_create_pair() IPC example

<?php
$ary
= array();
$strone = 'Message From Parent.' ;
$strtwo = 'Message From Child.' ;
if (!
socket_create_pair ( AF_UNIX , SOCK_STREAM , 0 , $ary )) {
    echo
socket_strerror ( socket_last_error ());
}
$pid = pcntl_fork ();
if (
$pid == - 1 ) {
    echo
'Could not fork Process.' ;
} elseif (
$pid ) {
    
/*parent*/
    
socket_close ( $ary [ 0 ]);
    if (!
socket_write ( $ary [ 1 ], $strone , strlen ( $strone ))) {
        echo
socket_strerror ( socket_last_error ());
    }
    if (
socket_read ( $ary [ 1 ], strlen ( $strtwo ), PHP_BINARY_READ ) == $strtwo ) {
        echo
"Recieved $strtwo \n " ;
    }
    
socket_close ( $ary [ 1 ]);
} else {
    
/*child*/
    
socket_close ( $ary [ 1 ]);
    if (!
socket_write ( $ary [ 0 ], $strtwo , strlen ( $strtwo ))) {
        echo
socket_strerror ( socket_last_error ());
    }
    if (
socket_read ( $ary [ 0 ], strlen ( $strone ), PHP_BINARY_READ ) == $strone ) {
        echo
"Recieved $strone \n " ;
    }
    
socket_close ( $ary [ 0 ]);
}
?>

Все функции PHP:
Авторизация
Логин

Пароль



Вы не зарегистрированы?
Нажмите здесь для регистрации.

Забыли пароль?
Запросите новый здесь.
Мини-чат
Вы должны авторизироваться, чтобы добавить сообщение.

12/04/2012 22:03
Это, в общем-то, нехороший признак

29/03/2012 18:52
Иногда хочется написать большими красными буквами, чтобы доходило быстрее Smile

29/03/2012 16:29
На форуме вопросы в основном ко мне, а я дальтоник

29/03/2012 15:31
Alipapa, а почему на форуме не включены цвета текста?

24/03/2012 18:38
Мультиблогом люди интересуются. Что имеется у нас?

02/03/2012 14:34
Как их запретить? Что-то в админке я не нашел, придется код править

23/02/2012 04:21
А ещё в голосованиях невозможно отредактировать опцию

23/02/2012 04:18
Alipapa, посмотри ГОЛОСОВАНИЯ НА ФОРУМЕ - почему у тебя там стоят по две кнопки "Обновить"?

23/02/2012 04:16
Желательно. Прилично.

21/02/2012 20:48
а это обязательно?

21/02/2012 19:23
Почему нет логотипа вверху на шапке? [img]http://ap-fus
ion.ru/images/news
_cats/ap-fusion.gi
f[/img]

13/02/2012 15:04
Всех влюблённых с праздником!!!

04/02/2012 09:08
Еще раз прошу всех. Если вопрос не личный, пишите в форум. В личке, аське, скайпе, мейле и т.д. не консультирую

14/01/2012 18:45
avisei, пиши в форум, а не шли мне личные посланья

31/12/2011 16:01
С праздником Нового Года! Успехов, счастья, богатства!

08/12/2011 16:13
MySQL нужен. Инструкция вот: [url]http://ap-fus
ion.ru/downloads.p
hp?download_id=58[
/url]

08/12/2011 16:03
Я канеш дико извиняюсь, но где на этом сайте статья по установке fusion, нужен ему MySql или нет? Smile

07/12/2011 11:03
ОК)

07/12/2011 11:02
этот - для 7.0

07/12/2011 11:00
Я устанавливаю, как в инструкции. Куча ошибок. Не могу сделать upgrade!

Анонс
Последние статьи
· О стабилизаторах нап...
· СМС и Вебмани
· TinyMCE для пользова...
· PCRE (Perl Compatibl...
· PCRE (Perl Compatibl...
4,796,399 уникальных посетителей Iceberg by Harly