# PHP和SOCKET

Socket基础
产生一个服务器
产生一个客户端

Socket 基础

PHP

AF_INET

AF_INET6

AF_UNIX

SOCK_STREAM

SOCK_DGRAM

SOCK_SEQPACKET

SOCK_RAW

SOCK_RDM

ICMP

UDP

TCP

Resourece socket_create(int protocol, int socketType, int commonProtocol);

<?php
$commonProtocol = getprotobyname(“tcp”);$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol); socket_bind($socket, ‘localhost’, 1337);
socket_listen($socket); // More socket functionality to come ?> 上面这个例子产生一个你自己的服务器端。例子第一行，$commonProtocol = getprotobyname(“tcp”);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 例子的第二行是产生一个socket并且返回一个socket资源的实例。在你有了一个socket资源的实例以后，你就必须把socket绑定到一个IP地址和某一个端口上。 socket_bind($socket, ‘localhost’, 1337);

socket_listen($socket); 在第四行以后，你就需要了解所有的socket函数和他们的使用。 表四：Socket函数 函数名 描述 socket_accept() 接受一个Socket连接 socket_bind() socket绑定在一个IP地址和端口上 socket_clear_error() 清除socket的错误或者最后的错误代码 socket_close() 关闭一个socket资源 socket_connect() 开始一个socket连接 socket_create_listen() 在指定端口打开一个socket监听 socket_create_pair() 产生一对没有区别的socket到一个数组里 socket_create() 产生一个socket，相当于产生一个socket的数据结构 socket_get_option() 获取socket选项 socket_getpeername() 获取远程类似主机的ip地址 socket_getsockname() 获取本地socketip地址 socket_iovec_add() 添加一个新的向量到一个分散/聚合的数组 socket_iovec_alloc() 这个函数创建一个能够发送接收读写的iovec数据结构 socket_iovec_delete() 删除一个已经分配的iovec socket_iovec_fetch() 返回指定的iovec资源的数据 socket_iovec_free() 释放一个iovec资源 socket_iovec_set() 设置iovec的数据新值 socket_last_error() 获取当前socket的最后错误代码 socket_listen() 监听由指定socket的所有连接 socket_read() 读取指定长度的数据 socket_readv() 读取从分散/聚合数组过来的数据 socket_recv() socket里结束数据到缓存 socket_recvfrom() 接受数据从指定的socket，如果没有指定则默认当前socket socket_recvmsg() iovec里接受消息 socket_select() 多路选择 socket_send() 这个函数发送数据到已连接的socket socket_sendmsg() 发送消息到 socket socket_sendto() 发送消息到指定地址的 socket socket_set_block() socket里设置为块模式 socket_set_nonblock() socket 里设置为非块模式 socket_set_option() 设置socket选项 socket_shutdown() 这个函数允许你关闭读、写、或者指定的socket socket_strerror() 返回指定错误号的详细错误 socket_write() 写数据到socket缓存 socket_writev() 写数据到分散/聚合数组 (: 函数介绍删减了部分原文内容，函数详细使用建议参考英文原文，或者参考PHP手册) 以上所有的函数都是PHP中关于socket的，使用这些函数，你必须把你的socket打开，如果你没有打开，请编辑你的php.ini文件，去掉下面这行前面的注释： extension=php_sockets.dll 如果你无法去掉注释，那么请使用下面的代码来加载扩展库： <?php if(!extension_loaded(‘sockets’)) { if(strtoupper(substr(PHP_OS, 3)) == “WIN”) { dl(‘php_sockets.dll’); } else { dl(‘sockets.so’); } } ?> 如果你不知道你的socket是否打开，那么你可以使用phpinfo()函数来确定socket是否打开。你通过查看phpinfo信息了解socket是否打开。如下图： 查看phpinfo()关于socket的信息 产生一个服务器 现在我们把第一个例子进行完善。你需要监听一个指定的socket并且处理用户的连接。 <?php$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM,$commonProtocol);
socket_bind($socket, 'localhost', 1337); socket_listen($socket);
// Accept any incoming connections to the server
$connection = socket_accept($socket);
if($connection) { socket_write($connection, "You have connected to the socket...\n\r");
}
?>

set_time_limit(0);

Php.exe example01_server.php

<?php
// Set up our socket
$commonProtocol = getprotobyname("tcp");$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol); socket_bind($socket, 'localhost', 1337);
socket_listen($socket); // Initialize the buffer$buffer = "NO DATA";
while(true)
{
// Accept any connections coming in on this socket

$connection = socket_accept($socket);
printf("Socket connected\r\n");
// Check to see if there is anything in the buffer
if($buffer != "") { printf("Something is in the buffer...sending data...\r\n"); socket_write($connection, $buffer . "\r\n"); printf("Wrote to socket\r\n"); } else { printf("No Data in the buffer\r\n"); } // Get the input while($data = socket_read($connection, 1024, PHP_NORMAL_READ)) {$buffer = $data; socket_write($connection, "Information Received\r\n");
printf("Buffer: " . $buffer . "\r\n"); } socket_close($connection);
printf("Closed the socket\r\n\r\n");
}
?>

This is what the server does. It initializes the socket and the buffer that you use to receive
and send data. Then it waits for a connection. Once a connection is created it prints
“Socket connected” to the screen the server is running on. The server then checks to see if
there is anything in the buffer; if there is, it sends the data to the connected computer.
After it sends the data it waits to receive information. Once it receives information it stores
it in the data, lets the connected computer know that it has received the information, and
then closes the connection. After the connection is closed, the server starts the whole
process again.

产生一个客户端

To solve the second problem is very easy. You need to create a PHP page that connects to
a socket, receive any data that is in the buffer, and process it. After you have processed the
data in the buffer you can send your data to the server. When another client connects, it
will process the data you sent and the client will send more data back to the server.

<?php
// Create the socket and connect
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);$connection = socket_connect($socket,’localhost’, 1337); while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ)) { if($buffer == “NO DATA”)
{
echo(“<p>NO DATA</p>”);
break;
}
else
{
// Do something with the data in the buffer
echo(“<p>Buffer Data: “ . $buffer . “</p>”); } } echo(“<p>Writing to Socket</p>”); // Write some test data to our socket if(!socket_write($socket, “SOME DATA\r\n”))
{
echo(“<p>Write failed</p>”);
}
// Read any response from the socket
while($buffer = socket_read($socket, 1024, PHP_NORMAL_READ))
{
echo(“<p>Data sent was: SOME DATA<br> Response was:” . \$buffer . “</p>”);
}