坚信科学,分享技术

2018全新版本,未来在blog.54chen.com更新博客!

>>>尝试更加利于阅读的2014版科学院,以后都在新版上写。

五四陈透过PHP看JAVA系列:fsockopen

本系列主要总结PHP与JAVA之间的一些异同,给从PHP学JAVA或者是从JAVA学PHP的同学一点启发,五四陈科学院出品。

第一部分,先看PHP的fsockopen

先来看PHP手册中的定义http://www.54chen.com/p/function.fsockopen.html

看完定义后,来看一段代码,利用PHP去更新squid的缓存:

<?php
function updateCache($myUrl) {
global $vSquidConfig;
foreach ( $vSquidConfig ['host'] as $mySquid ) {
$myHandle = @fsockopen ( "127.0.0.1", 80, $myErrNo, $myErrStr, 30 );
if ($myHandle) {
$myResult = '';
@fputs ( $myHandle, "PURGE " . $myFileName . " HTTP/1.0\r\n" );
@fputs ( $myHandle, "Accept: */*\r\n" );
@fputs ( $myHandle, "\r\n\r\n" );
while ( ! feof ( $myHandle ) ) {
$myResult .= fgets ( $myHandle, 128 );
}
@fclose ( $myHandle );
}
}
}
?>

第二部分,再看JAVA如何达到这个目的

public void flushSquid() {
try {
int port = 80;
Socket socket = new Socket("127.0.0.1", port);
String path = http://test.com/test.html";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
wr.write("PURGE " + path + " HTTP/1.0\r\n");
wr.write("Accept: */*\r\n");
wr.write("\r\n\r\n");

wr.flush();

// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
}
}

亲爱的读者,您喜欢用PHP还是JAVA?


原创文章如转载,请注明:转载自五四陈科学院[http://www.54chen.com]
本文链接: http://www.54chen.com/php-tech/54-chen-through-php-to-see-java-series-fsockopen.html

This entry was posted in java, php and tagged , , . Bookmark the permalink.

4 Responses to “五四陈透过PHP看JAVA系列:fsockopen”

  1. laruence 说:

    这种比较,,能比出来什么.

  2. cc0cc 说:

    从一种语言转另一种语言的时候,特别都想去用前一种的方式思考问题,找解决方案,这比较适合从PHP转JAVA的同志参考代码

Leave a Reply