PHP socket_bind错误(套接字地址只有一种用法)

时间:2013-07-10 14:59:50

标签: php sockets

下面是我创建的用于侦听传入消息(XML字符串)的PHP脚本。

PHP脚本托管在我的本地家庭服务器端口13330上,这样我就可以收听传入的请求,对吗?所以我创建了套接字并将其绑定到文件所在的地址。

我收到此错误:警告:socket_bind():无法绑定地址[0]:通常只允许使用每个套接字地址(协议/网络地址/端口)。

如果有人能让我知道为什么我会看到这一点,我将不胜感激。

由于

createSocketServer();

function createSocketServer() {

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

    // Set the ip and port we will listen on
    $address = '127.0.0.1';
    $port = 13330;

    // Create a TCP Stream socket
    $sock = socket_create(AF_INET, SOCK_STREAM, 0);
    echo '<p>Socket created</p>';

    // Bind the socket to an address/port
    socket_bind($sock, $address, $port) or die('Could not bind to address');
    echo '<p>Socket binded</p>';

    // Start listening for connections
    socket_listen($sock);
    echo '<p>Socket listening</p>';

    /* Accept incoming requests and handle them as child processes */
    $client = socket_accept($sock);

    // Read the input from the client &#8211; 1024 bytes
    $input = socket_read($client, 1024);

    // Strip all white spaces from input
    $output = ereg_replace("[ \t\n\r]","",$input).chr(0);
    echo $output;
}

1 个答案:

答案 0 :(得分:0)

在绑定之前使用此代码:

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($socket));
    exit;
}

供参考http://www.php.net/manual/en/function.socket-bind.php

您还可以查看http://www.php.net/manual/en/function.socket-set-option.php了解详情