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


Socket connection to localhost is timing out

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

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

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

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

端口转发

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

阿帕奇

Listening on port Y

白名单

Added IP X

当我在 online.com 上运行 php 脚本时

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..

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

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

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

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