dongtan6695 2015-11-11 16:57
浏览 37
已采纳

PHP套接字,无法连接 - 循环?

Hello i'm trying to learn and build a socket script in PHP this is my code:

Client:

include_once('server.php');

$host = "localhost"; 
$port    = 1025;

$message = "Hello Server";

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false) { 
 echo "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "
";
 }
// connect to server
    socket_bind($socket, $host);
    if (socket_connect($socket, $host, $port) === false) { 
         echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error($socket)) . "
";
    }
    else { echo "Connected"; }

Server:

// Variables 
$host = "localhost"; 
$port = 1025; 

// No timeout 
set_time_limit(0); 

// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Can't create socket..");

if ($socket === false) {
    echo "Unable to create socket. Error: {$errno} : {$errstr}
"; 
    die();
}


// Bind Socket
if (socket_bind($socket, $host) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "
";
}
else { echo "Connected to {$host}:{$port}"; }

// Socket listen
if (socket_listen($socket, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "
";
}

if (socket_accept($socket) === false) {
    echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($socket)) . "
";
}



// Socket close
socket_close($socket);

But i'm missing something that i cant figure out and i dont know what, When im trying to connect from the client it just loads nothing happens, Can anyone here point me in the right direction and tell me what im doing wrong?

  • 写回答

2条回答 默认 最新

  • drl959975 2015-11-11 18:14
    关注

    On your client, you do not want socket_bind(). That is for opening up a connection for other systems to connect to; in short, to become a server.

    Our client script:

    <?php // client.php
    $host = "127.0.0.1"; // connect _does_ do DNS lookups, unlike bind, which is mentioned below, but for simplicity of the example I'm explicitly naming the IP address.
    $port    = 1025;
    $message = "Hello Server";
    
    // create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, 0);
    if ($socket === false) {
        // Using die() here because we really don't want to continue on while in an error condition.
        die('socket_create() failed: reason: ' . socket_strerror(socket_last_error($socket));
    }
    
    // connect to server
    if (socket_connect($socket, $host, $port) === false) { 
         die('socket_connect() failed: reason: ' . socket_strerror(socket_last_error($socket));
    }
    
    socket_write($socket, $message);
    socket_close($socket);
    

    In your server, you should listen on 0.0.0.0 (or a specific IP address), and not specify a domain name. 0.0.0.0 means to listen to all IP addresses, and any specific IP address means to only listen on the one interface that is configured for that address.

    For example, if your server has 2 NICs, one assigned to a public address, say 1.2.3.4, and another assigned to a local address, 192.168.0.2. You also always have your loopback, 127.0.0.1 for free just by having TCP/IP.

    If you want to restrict access to your server script to only other hosts on your network, you would set your listen address to 192.169.0.2. Even though your server is accessible through the public IP of 1.2.3.4, this script will simply not listen to any of that traffic.

    If you want to restrict access to your server script to only other processes running on that machine, you need to use 127.0.0.1. Using "localhost" will not keep anyone out, because bind does not perform any DNS lookups (and PHP's socket_bind() is only a thin wrapper around the BSD Sockets based system call to bind). It doesn't even look at the hosts file. Thus, any non-IP string will be cast to an integer, usually resulting in it becoming 0, and that 0 will be converted to 0.0.0.0, which will allow access from all interfaces, despite you thinking that you're only listening to localhost traffic.

    When you accept a connection, it creates a new socket resource, which I've named $clientSocket in the example below. Don't get confused between the sockets created when a new host connects and your listening socket; they're very similar, but with a very important distinction: When your listening socket has a new message, it is always saying that there is a new host connecting, so you should accept. If it is a client socket, then you'll be using read or recv. (I prefer recv because of the finer control, but I use read in the example below to more clearly show the process rather than adding confusion by having references... which is also why I'm not going to show select.)

    Our server script:

    <?php //server.php
    $listen_address = "0.0.0.0";
    $port = 1025; 
    $maxBuffer = 1024; // bytes, not characters.
    
    // No timeout 
    //set_time_limit(0); // Shouldn't be necessary in CLI.
    
    // Create socket
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    
    if ($socket === false) {
        die('Unable to create socket: ' . $socket_strerror(socket_last_error($socket)) . PHP_EOL);
    }
    
    // Bind Socket
    if (socket_bind($socket, $listen_address, $port) === false) {
        die('socket_bind() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
    }
    else { 
        echo "Connected to {$listen_address}:{$port}
    "; 
    }
    
    // Accept our client connection
    
    // Typically, this would be where we'd put a loop with socket_select,
    // but for our example, since we'll be exiting as soon as we have our
    // first packet, we'll listen, accept, read, then close.
    if (socket_listen($socket) === false) {
        die('socket_listen() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
    }
    
    $clientSocket = socket_accept($socket);
    if ($clientSocket === false) {
        die('socket_accept() failed: ' . socket_strerror(socket_last_error($socket)) . PHP_EOL);
    }
    
    // Because the contents of a packet could be longer than our
    // buffer size, it's advisable to peek at the socket to see
    // if it would block before saying that our message is complete.
    // In our example, we're receiving 12 bytes out of our maximum 1024,
    // so I leave handling large packets as an exercise for the developer.
    $message = socket_read($clientSocket, $maxBuffer);
    
    var_dump($message);
    
    // Socket close
    socket_close($clientSocket);
    socket_close($socket);
    

    And finally, here's how to run the mess above.

    Note that I'm going to have both the server and client run in the same TTY, I'll have the server run as a background process (use the & modifier), but I will not be redirecting their output, so both scripts will be spitting their output into the same terminal.

    myhost.mydomain$ php ./server.php &
    [8] 76399
    Connected to 0.0.0.0:1025
    myhost.mydomain$ php ./client.php
    string(12) "Hello Server"
    [8]+  Done                    php ./server.php
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?