简体   繁体   English

TCP / IP连接的PHP套接字错误

[英]PHP socket error for TCP/IP connection

I am trying to make a simple TCP/IP connection to a given IP and Port using sockets in PHP. 我试图使用PHP中的套接字与给定的IP和端口建立简单的TCP / IP连接。

I am getting an error message that says "A non-blocking socket operation could not be completed immediately." 我收到一条错误消息,指出“无法立即完成非阻塞套接字操作”。 below is my code: 下面是我的代码:

<?php
$address = 'myhost.com';
$service_port = 1234;
$timeout = 1000;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($socket);
$error = NULL;
$attempts = 0;
while (!($connected = @socket_connect($socket, $address, $service_port)) && ($attempts < $timeout)) {
    $error = socket_last_error();
    if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
          echo socket_strerror($error) . "\n";
          socket_close($socket);
          return NULL;
    }
    usleep(1000);
    $attempts++;
}
?>

any ideas? 有任何想法吗? i know there are no issues with the target host ip or port. 我知道目标主机IP或端口没有问题。

You are calling connect() on a non-blocking socket. 您在非阻塞套接字上调用connect() The connect() call will always need to block to complete its operation, and since you explicitly told the socket to be non-blocking it immediately returns with an error telling you that it did not (yet) complete its operation. connect()调用将始终需要阻塞以完成其操作,并且由于您明确告知套接字是非阻塞的,因此它会立即返回并显示错误,告知您它尚未完成其操作。

You are a bit at the mercy of the OS you are using when using sockets directly. 在使用套接字时,您有点受到操作系统的支配。 The code looks good overall. 代码整体看起来不错。 You will retry the connect until you get EINPROGRESS . 您将重试连接,直到您获得EINPROGRESS Is that indeed the error code you are seeing? 这确实是你看到的错误代码吗? Maybe you are checking for the wrong error code? 也许您正在检查错误的错误代码?

Anyway your code looks to me like you try to connect until the connection is established. 无论如何,你的代码看起来像你尝试连接,直到建立连接。 You can use blocking mode directly to achieve that. 您可以直接使用阻止模式来实现这一点。

Just leave the socket as blocking until you connected it and set the socket to non-blocking (assuming you really need that) after it is connected. 只需将套接字保持为阻塞状态,直到连接它并在连接后将套接字设置为非阻塞(假设您确实需要它)。

non-blocking socket usually used for servers, servers are waiting for connection, so instead of using socket_connect , try using socket_listen instead 通常用于服务器的非阻塞套接字,服务器正在等待连接,所以不要使用socket_connect ,而是尝试使用socket_listen代替

if you want to establish a connection to a server (be a client) then use Johannes's suggestion 如果要建立与服务器(客户端)的连接,请使用Johannes的建议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM