五四陈透过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]

捐款订阅54chen
捐赠说明

Comments