2016-07-15 103 views
2

所以我試圖讓在託管網站(姑且稱之爲online.com),以能夠從我的Apache本地(WAMP)抓住一些文本文件。Socket連接到本地主機已超時

然而,當我運行的代碼online.com負載了一會兒,然後提出錯誤100(超時)。我不知道爲什麼。

我使用套接字來做到這一點。我在PC的防火牆上將online.com的ip列入了白名單。我已將偵聽端口添加到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 

當我運行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); 

該行​​是問題的原因。

任何關於什麼可能是錯誤的建議將不勝感激。

+0

什麼是錯誤信息?是否die()在連接失敗後返回特定錯誤? – gladiola

回答

0

你爲什麼使用套接字?只需使用file_get_contents()向您的家庭IP發送常規HTTP請求即可。

例,

<?php 

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

我會盡力,非常感謝。讓你知道它怎麼走 – devonrimmington

+0

這個解決方案正是我所需要的。我只需要更改一些Apache設置並打開正確的端口,但現在我可以從手機訪問!我已經接受你的回答 – devonrimmington

0

對不起,我現在認爲這是客戶端代碼實現。

連接方法通常會休眠,直到從服務器發送適當的答案。你見證了套接字服務器程序試圖響應這個客戶端嗎?一種檢查方法是讓服務器端寫入代表每個連接嘗試的日誌條目。

如果代碼只是坐在那裏,並沒有提供錯誤,它可能只是在等待,因爲它應該。

起草時在插座客戶端 - 服務器系統的實驗代碼,它可以幫助在像每一個關口,以檢查錯誤:連接,綁定,發送,接收,傾聽,接受和關閉。

+0

在我向前推進涉及套接字的其他事情之前,我將嘗試凱里的解決方案 – devonrimmington