Class sock
{
var $socket;
var $port;
var $address;
function Connect()
{
return socket_connect($this->socket, $this->address, $this->port);
}
function ReadMsg()
{
$out=socket_read($this->socket, 1024,PHP_BINARY_READ);
$out=iconv("big5","utf8",$out);
return $ans;
}
function SendMsg($msg)
{
$timeout = 30;
socket_write($this->socket, $msg, strlen($msg));
$ans="";
while (1)
{
$out=socket_read($this->socket, 1024,PHP_BINARY_READ);
if ($out=="") $timeout --;
echo ".";
$out=iconv("big5","utf8",$out);
$ans.=$out;
if ($timeout<=0) { echo "break\n"; break; }
if(socket_last_error($this->socket) == 104) echo "Connection closed";
}
return $ans;
}
function Close()
{
return socket_close($this->socket);
}
}
$s = new sock();
$s->port = getservbyname('telnet', 'tcp');
$s->address = gethostbyname('ptt.cc');
$s->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = $s->Connect();
$response = $s->SendMsg("antontw\r\n\r\n");
echo "'".strlen($response)."'\n";
flush();
$result = $s->Close();
?>
然而,我試了幾次,這個範例還不是很好用,直到發現有人開發了 PHP Telnet 這個物件, 似乎又重新打開了希望。
這個物件在測試 SayYa的時候沒有什麼大問題,不過在測試 PTT的時候發生了一些狀況,看起來還是有很多地方要注意。
以下是應用的範例:
require_once "PHPTelnet.php";
function arraytostring($array, $depth = 0)
{
if (!is_array($array)) return $array;
if($depth > 0)
$tab = implode('', array_fill(0, $depth, "\t"));
$text.="array(\n";
$count=count($array);
foreach ($array as $key=>$value)
{
$x++;
if (is_array($value))
{
if(substr($text,-1,1)==')') $text .= ',';
$text.=$tab."\t".'"'.$key.'"'." => ".arraytostring($value, $depth+1);
continue;
}
$text.=$tab."\t"."\"$key\" => \"$value\"";
if ($count!=$x) $text.=",\n";
}
$text.="\n".$tab.")\n";
if(substr($text, -4, 4)=='),),')$text.='))';
return $text;
}
//$out = iconv("big5","utf8",$arr[$i]);
$telnet = new PHPTelnet();
$telnet->show_connect_error=0;
$result = $telnet->Connect('ptt.cc','antontw','密碼!');
if ($result==0) echo "開始下命令\n"; else echo "有錯誤\n";
$telnet->DoCommand('q', $result);
$ans = arraytostring($result);
$ans = iconv("big5","utf8",$ans);
echo $ans;
echo "\n正常退出\n";
$telnet->Disconnect();
?>
沒有留言:
張貼留言