与本地主机的套接字连接超时

Socket connection to localhost is timing out

所以我试图获得一个托管网站(我们称之为 online.com),以便能够从我的 Apache 本地 (WAMP) 获取一些文本文件。

然而,当我 运行 代码 online.com 加载一段时间后,出现错误 100(超时)。不知道为什么。

我正在使用套接字来执行此操作。我已经在我电脑的防火墙上将 online.com 的 IP 列入白名单。我已经将侦听端口添加到 Apache 服务器。我已经完成了端口转发(虽然我不能 100% 确定我是否正确完成)。

以下是上述内容的更具象征意义的表示。

端口转发

online.com's IP = X, port = 80
local host's IP = (used ipconfig) IPV4 Address, port = Y

Apache

Listening on port Y

白名单

Added IP X

当我 运行 php 脚本在 online.com

if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Connect socket to remote server


**if (!socket_connect($sock, 'IP X', PORTY))**
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";
$message = "GET / PRCC /HTTP/1.1 \r\n\r\n";

// Send the message to the server

if (!socket_send($sock, $message, strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not send data: [$errorcode] $errormsg \n");
}

echo "Message send successfully \n";
$buf = "";

// Now receive reply from server

if (socket_recv($sock, $buf, 2045, MSG_WAITALL) === FALSE)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    die("Could not receive data: [$errorcode] $errormsg \n");
}

// print the received message

echo $buf . "this is the buffer";
socket_close($sock);

if(!socket_connect($sock , 'IP X' , PORT Y)) 行是问题的原因。

任何关于错误的建议将不胜感激。

为什么要使用套接字?只需尝试使用 file_get_contents().

向您的家庭 IP 发出常规 HTTP 请求

示例,

<?php

$text_file1 = file_get_contents("http://YOUR_IP:PORT/PRCC");
// so on..

对不起,我现在意识到这是客户端代码。

连接方法通常会休眠,直到从服务器发送适当的应答。您是否看到套接字服务器程序试图响应此客户端?一种检查方法是让服务器端写入一个代表每次连接尝试的日志条目。

如果代码就在那里,没有提供错误,它可能只是在等待。

在为套接字中的客户端-服务器系统起草实验代码时,它可以帮助检查每个关键点的错误,例如:连接、绑定、发送、接收、侦听、接受和关闭。