如何用PHP实现Socket服务器

发布时间:2020-04-29 08:19    浏览次数 :

[返回]

澳门新葡亰平台游戏,本文由码农网 – 王国峰原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划!

socket服务器的工作方式是这样的,不间断地运行以等待客户端的连接。一旦客户端连接上了,服务器就会将它添加到客户名单中,然后开始等待来自客户端的消息。

想要构建聊天应用,或者甚至是游戏吗?那么,socket服务器将成为你迈出的第一步。一旦你了解了创建服务器的基本功能,那么后续的优化步骤就会变得同样简单。

不要走开,下面是完整的源代码:

socket服务器的工作方式是这样的,不间断地运行以等待客户端的连接。一旦客户端连接上了,服务器就会将它添加到客户名单中,然后开始等待来自客户端的消息。

// Set time limit to indefinite execution set_time_limit ; // Set the ip and port we will listen on $address = 'localhost'; $port = 10000; $max_clients = 10; // Array that will hold client information $client = Array(); // Create a TCP Stream socket $sock = socket_create(AF_INET, SOCK_STREAM, 0); // Bind the socket to an address/port socket_bind($sock, $address, $port) or die('Could not bind to address'); // Start listening for connections socket_listen; echo "Waiting for connections...rn"; // Loop continuously while  { // Setup clients listen socket for reading $read[0] = $sock; for ($i = 0; $i < $max_clients; $i++) { if (isset $read[$i + 1] = $client[$i]['sock']; } // Set up a blocking call to socket_select() if (socket_select($read, $write = NULL, $except = NULL, $tv_sec = 5) < 1) continue; /* if a new connection is being made add it to the client array */ if (in_array { for ($i = 0; $i < $max_clients; $i++) { if (empty { $client[$i]['sock'] = socket_accept; echo "New client connected $irn"; break; } elseif ($i == $max_clients - 1) echo "Too many clients...rn"; } } // end if in_array // If a client is trying to write - handle it now for ($i = 0; $i < $max_clients; $i++) { // for each client if (isset { if (in_array($client[$i]['sock'], $read)) { $input = socket_read($client[$i]['sock'], 1024); if  { echo "Client disconnecting $irn"; // Zero length string meaning disconnected unset; } else { echo "New input received $irn"; // send it to the other clients for ($j = 0; $j < $max_clients; $j++) { if (isset && $j != $i) { echo "Writing '$input' to client $jrn"; socket_write($client[$j]['sock'], $input, strlen; } } if  { // requested disconnect socket_close; } } } else { echo "Client disconnected $irn"; // Close the socket socket_close; unset; } } } } // end while // Close the master sockets socket_close; 

澳门新葡亰平台游戏 1

哎呀,乍一看这似乎是一个大工程,但是我们可以先将它分解为几个较小的部分。

不要走开,下面是完整的源代码:

第一部分是创建服务器。Lines:2至20。

// Set time limit to indefinite execution
set_time_limit (0);

// Set the ip and port we will listen on
$address = 'localhost';
$port = 10000;
$max_clients = 10;

// Array that will hold client information
$client = Array();

// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');
// Start listening for connections
socket_listen($sock);

echo "Waiting for connections...rn";

// Loop continuously
while (true) {
    // Setup clients listen socket for reading
    $read[0] = $sock;
    for ($i = 0; $i < $max_clients; $i++) {
        if (isset($client[$i]['sock']))
            $read[$i + 1] = $client[$i]['sock'];
    }
    // Set up a blocking call to socket_select()
    if (socket_select($read, $write = NULL, $except = NULL, $tv_sec = 5) < 1)
        continue;
    /* if a new connection is being made add it to the client array */
    if (in_array($sock, $read)) {
        for ($i = 0; $i < $max_clients; $i++) {
            if (empty($client[$i]['sock'])) {
                $client[$i]['sock'] = socket_accept($sock);
                echo "New client connected $irn";
                break;
            }
            elseif ($i == $max_clients - 1)
                echo "Too many clients...rn";
        }
    } // end if in_array

    // If a client is trying to write - handle it now
    for ($i = 0; $i < $max_clients; $i++) { // for each client
        if (isset($client[$i]['sock'])) {
            if (in_array($client[$i]['sock'], $read)) {
                $input = socket_read($client[$i]['sock'], 1024);
                if ($input == null) {
                    echo "Client disconnecting $irn";
                    // Zero length string meaning disconnected
                    unset($client[$i]);
                } else {
                    echo "New input received $irn";
                    // send it to the other clients
                    for ($j = 0; $j < $max_clients; $j++) {
                        if (isset($client[$j]['sock']) && $j != $i) {
                            echo "Writing '$input' to client $jrn";
                            socket_write($client[$j]['sock'], $input, strlen($input));
                        }
                    }
                    if ($input == 'exit') {
                        // requested disconnect
                        socket_close($client[$i]['sock']);
                    }
                }
            } else {
                echo "Client disconnected $irn";
                // Close the socket
                socket_close($client[$i]['sock']);
                unset($client[$i]);
            }
        }
    }
} // end while
// Close the master sockets
socket_close($sock);

这部分代码设置了变量、地址、端口、最大客户端和客户端数组。接下来创建socket并将其绑定到我们指定的地址和端口上。

啊呀,乍一看这似乎是一个大工程,但是我们可以先将它分解为几个较小的部分。第一部分是创建服务器。Lines:2至20。

下面我们要做的事情就是执行一个死循环。Lines:22至32。

这部分代码设置了变量、地址、端口、最大客户端和客户端数组。接下来创建socket并将其绑定到我们指定的地址和端口上。

在这部分代码中我们做的第一步是设置 $read 数组。此数 组包含所有客户端的套接字和我们主服务器的套接字。这个变量稍后会用于select语句:告诉PHP监听来自这些客户端的每一条消息。

下一篇:没有了