实现的功能是将后台产生的日志文件读取到客户端sokect中,并显示出来
package code.thread;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.Socket;
public class RunStatusThread extends Thread{
private Socket clientRequestStatus; //客户端套接字
private PrintWriter output; //向文本输出流打印对象的格式化表示形式
//构造函数
public RunStatusThread(Socket clientRequestStatus){
this.clientRequestStatus = clientRequestStatus;
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public void run(){
String aFile = "forPath";
File f = new File(aFile);
//创建文件后得到path为/home/gxudonghe/workspace/HDVer/forPath
String path = f.getAbsoluteFile().toString();
try {
output = new PrintWriter(new OutputStreamWriter(clientRequestStatus.getOutputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
output.println("Welcome to the Status Server! Now is "+new java.util.Date()+" "+"Port: "+clientRequestStatus.getLocalPort());
output.println("=========================The log information is============================");
output.flush();
// 用创建一个文件的方法,得出当前的目录为/home/gxudonghe/workspace/HDVer/,类型为字符串
String curDir = path.substring(0, path.indexOf(aFile));
String fileName=curDir+"Daemon_log.txt";
File file = new File(fileName);
try {
//实用随机文件读取的方法来处理不断增长的文件
RandomAccessFile raf=new RandomAccessFile(file,"r");
// 获取当前文件的总长度
long fileLen=0;
long strSumLen=0;
while (true) {
raf.getFilePointer();
String tempString=raf.readLine();
if(null!=tempString){
output.println( tempString);
output.flush();
strSumLen+=tempString.length();
}
fileLen=raf.length();
if(fileLen<=strSumLen){
sleep(1000);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
纠结了好久才搞定,因为如果不使用RandomAccessFile对象,客户端读到的文件都是部分长度,新增的并没有读取。客户端的代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class StatusCommand {
/**
* @param args
*/
public static void main(String[] args) {
try{
Socket socket=new Socket("192.168.1.110",56533);
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(is.readLine()!=null)
{
String responseline=is.readLine();
System.out.println(responseline);
}
is.close();
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}