使用Netty搭建的服务端,主要用于文件处理和json处理

来源:互联网 发布:蚁群算法应用 编辑:程序博客网 时间:2024/05/17 00:04


使用Netty搭建的服务端,主要用于文件处理和json处理


    单例模式设计该类:
    public static SocketFileServer getInstance() {
if (instance == null)
instance = new SocketFileServer();
return instance;
}

该类成员属性:
private static SocketFileServer instance;
public static String ip = "127.0.0.1";// socket命令IP ---- 192.168.43.1
private static final int PORT = 8787;// socket命令端口
public ChannelFuture future = null;// 用于写入


public  ServerBootstrap bootstrap;//服务端Netty必须实现
private Channel channel = null;


必须进行的初始化处理:
   bootstrap = new ServerBootstrap((ChannelFactory) new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
   
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());


Timer timer = new HashedWheelTimer();  
pipeline.addLast("timeout", new ReadTimeoutHandler(timer, 60 * 60 * 10)); 
pipeline.addLast("handler", new FileTransferChannelHandler());

return pipeline;
}
});
   
    if (channel == null) {
// 创建服务器端channel的辅助类,接收connection请求
System.out.println("bind 8787 service");
channel = bootstrap.bind(new InetSocketAddress(ip, PORT));

System.out.println("----8787 port server----" + future);


自定义ChannelHandler类:
FileTransferChannelHandler
class FileTransferChannelHandler extends SimpleChannelHandler{


  //   private  FileTransferChannelHandler instanceChannelHandler = null;
    public FileTransferChannelHandler(){
    SocketCommandServer.getInstance().setOnDownLoaderListener(new downloadListener());
    }
   
   
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
// TODO Auto-generated method stub
System.out.println("----8787 port server----" + "channelClosed");
super.channelClosed(ctx, e);

instance = null;
getInstance();
}


@Override
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// TODO Auto-generated method stub
System.out.println("----8787 port server----" + " channelConnected  ");
// // 用于检测和客户端的连接状态。
// if (channel != null){
// channel.write("{\"port\":8787,\"ip\":127.0.0.1,\"status\":\"open\"}");
// } else if (e.getChannel() != null){
// channel.write("{\"port\":8787,\"ip\":127.0.0.1,\"status\":\"open\"}");
// }
channelHandlerContext = ctx;
super.channelConnected(ctx, e);
}


@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// TODO Auto-generated method stub
System.out.println("----8787 port server----" + " channelDisconnected  ");
super.channelDisconnected(ctx, e);
}


@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
// TODO Auto-generated method stub
String megString = e.getCause().toString();
System.out.println("----8787 port server----exceptionCaught----" + megString);
super.exceptionCaught(ctx, e);
ctx.getChannel().close();
}


@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
// TODO Auto-generated method stub



super.messageReceived(ctx, e);
}
   
    }

用于监听的下载文件的回调:
public interface IDownLoaderListenning {

void onDownLoader(String filePath, String fileName);//int:
void onDownLoader(String arg0);//arg0:文件的完整路径名

int get_file_complete = 1;
int get_file_exception = -1;


    }

下面给出该类完整的代码:
package com.aprkuatang.netty.socketfileserver;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;


import com.aprkuatang.netty.interfacecallback.IDownEventListenning;
import com.aprkuatang.netty.interfacecallback.IDownLoaderListenning;
import com.aprkuatang.netty.socketserver.SocketCommandServer;




public class SocketFileServer {

private static SocketFileServer instance;
public static String ip = "127.0.0.1";// socket命令IP ---- 192.168.43.1
private static final int PORT = 8787;// socket命令端口
public ChannelFuture future = null;


public  ServerBootstrap bootstrap;
Channel channel = null;

private String downfile = "";
public Object objLock = new Object();
private boolean isStartDown = false;

private Lock lock = new ReentrantLock();//可重入锁,可根据情况就解锁,必须有解锁,建议使用try{}catch{}finally{}
private byte[] byteLockObj = new byte[0];

ChannelHandlerContext channelHandlerContext;

    public static SocketFileServer getInstance() {
if (instance == null)
instance = new SocketFileServer();
return instance;
}
    
    private SocketFileServer() {
    if (ip.equals("")){
    return ;
    }
   
    bootstrap = new ServerBootstrap((ChannelFactory) new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
   
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());


Timer timer = new HashedWheelTimer();  
pipeline.addLast("timeout", new ReadTimeoutHandler(timer, 60 * 60 * 10)); 
pipeline.addLast("handler", new FileTransferChannelHandler());

return pipeline;
}
});
   
    if (channel == null) {
// 创建服务器端channel的辅助类,接收connection请求
System.out.println("bind 8787 service");
channel = bootstrap.bind(new InetSocketAddress(ip, PORT));

System.out.println("----8787 port server----" + future);

    }
    
    
    class FileTransferChannelHandler extends SimpleChannelHandler{


  //   private  FileTransferChannelHandler instanceChannelHandler = null;
    public FileTransferChannelHandler(){
    SocketCommandServer.getInstance().setOnDownLoaderListener(new downloadListener());
    }
   
   
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
// TODO Auto-generated method stub
System.out.println("----8787 port server----" + "channelClosed");
super.channelClosed(ctx, e);

instance = null;
getInstance();
}


@Override
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// TODO Auto-generated method stub
System.out.println("----8787 port server----" + " channelConnected  ");
// // 用于检测和客户端的连接状态。
// if (channel != null){
// channel.write("{\"port\":8787,\"ip\":127.0.0.1,\"status\":\"open\"}");
// } else if (e.getChannel() != null){
// channel.write("{\"port\":8787,\"ip\":127.0.0.1,\"status\":\"open\"}");
// }
channelHandlerContext = ctx;
super.channelConnected(ctx, e);
}


@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// TODO Auto-generated method stub
System.out.println("----8787 port server----" + " channelDisconnected  ");
super.channelDisconnected(ctx, e);
}


@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
// TODO Auto-generated method stub
String megString = e.getCause().toString();
System.out.println("----8787 port server----exceptionCaught----" + megString);
super.exceptionCaught(ctx, e);
ctx.getChannel().close();
}


@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
// TODO Auto-generated method stub



super.messageReceived(ctx, e);
}
   
    }
    
    IDownEventListenning listenning = null;
public void setOnDownListener(IDownEventListenning arg0){
this.listenning = arg0; 
}
    
    class downloadListener implements IDownLoaderListenning{


@Override
public void onDownLoader(String filePath, String fileName) {
// TODO Auto-generated method stub
   lock.lock();
downfile = filePath + fileName;
isStartDown = true;
System.out.println("----8787----downfile----" + downfile);
downLoaderEvent(channelHandlerContext);
}


@Override
public void onDownLoader(String arg0) {
// TODO Auto-generated method stub
lock.lock();
downfile = arg0;
isStartDown = true;
System.out.println("----8787----downfile----" + downfile);
downLoaderEvent(channelHandlerContext);
}
   
    }
    
    /** 进行文件下载的参数处理,主要是文件路径和文件名 **/
private void downLoaderEvent(ChannelHandlerContext ctx){
    final ChannelHandlerContext channelServer = ctx;
    if (channelServer == null){
    System.out.println("通道空");
    return ;
    }
    System.out.println("----8787----chanelServer----" + channelServer);
    File file = new File(downfile);
    BufferedInputStream bis = null;
    int line;
    byte[] mBuffer = new byte[1024 * 2];
   
    int count = 0;//计数
   
   
    if (file.exists()){
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        bis = new BufferedInputStream(fileInputStream);
        try {
while ((line = bis.read(mBuffer)) != -1){
                                    System.out.println("----SocketFileServer----line = " + line);
ChannelBuffer buffer = ChannelBuffers.copiedBuffer(mBuffer, 0, line);

channelServer.getChannel().write(buffer);
System.out.println("transfer file server----" + "line = " + line + "----计数次数 ----------" + (count++));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
       
        } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       
        } finally{
        isStartDown = false;
        lock.unlock();
        }
   
   
    } else {
    lock.unlock();
    }
    }//end


}


    另一个用于处理字符串问题的服务端代码,依旧采用Netty搭建,上面的内容主要是针对于文件传输所搭建的服务端代码,二者有区别:
package com.aprkuatang.netty.socketserver;


import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.util.TimerTask;
import java.util.concurrent.Executors;


import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;


import com.aprkuatang.netty.interfacecallback.IDownLoaderListenning;
import com.aprkuatang.netty.socketfileserver.CollectorPath;
import com.aprkuatang.netty.socketfileserver.ReadAndWriteFile;
import com.google.gson.stream.JsonReader;


/** 7878服务器端口 **/
public class SocketCommandServer {

private static SocketCommandServer instance;
public static String ip = "127.0.0.1";// socket命令IP ---- 192.168.43.1
private int port = 7878;// socket命令端口
public ChannelFuture future = null;


public  ServerBootstrap bootstrap;
public Channel channel = null;

private IDownLoaderListenning iDownLoaderListenning = null;

    public static SocketCommandServer getInstance() {
if (instance == null)
instance = new SocketCommandServer();
return instance;
}
    
    public void postCommand(String strCommand){
    if (future != null && future.getChannel() != null){
    future.getChannel().write(strCommand);
    } else {
instance = new SocketCommandServer();
}
    }
    
    public void setOnDownLoaderListener(IDownLoaderListenning listener){
    this.iDownLoaderListenning = listener;
    }
    
    public void disConnect() {
    if (null != future && null != future.getChannel() && future.getChannel().isOpen()
&& future.getChannel().isConnected()) {
future.getChannel().unbind();
future.getChannel().close();
}
    }
    
    private SocketCommandServer() {
    if (ip.equals("")){
    return ;
    }
   
    bootstrap = new ServerBootstrap((ChannelFactory) new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
   
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());


Timer timer = new HashedWheelTimer();  
pipeline.addLast("timeout", new ReadTimeoutHandler(timer, 60 * 60 * 10)); 
pipeline.addLast("handler", new CommandChannelHandler());

return pipeline;
}
});
   
    if (channel == null) {
// 创建服务器端channel的辅助类,接收connection请求
System.out.println("bind service");
channel = bootstrap.bind(new InetSocketAddress(ip, port));

System.out.println("future----" + future);

    }
    
    
    class CommandChannelHandler extends SimpleChannelHandler{
    @Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
// TODO Auto-generated method stub


   System.out.println("-----------socketcommandserver Ip channelClosed-----------");


super.channelClosed(ctx, e);
}


@Override
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// TODO Auto-generated method stub
System.out.println("---------IpchannelConnected--------");
super.channelConnected(ctx, e);
instance = null;
getInstance();
}


public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
String message = (String) e.getMessage();

System.out.println(this.getClass().getCanonicalName().toString() + "-----------" + message);
responseMessage(ctx, message);
   }


public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("------socket command server 7878 exceptionCaught------" + e.getCause());

e.getChannel().close();
}

int i = 0;
private synchronized void responseMessage(ChannelHandlerContext ctx, String messageEvent){
final ChannelHandlerContext channelHandlerContext = ctx;

String msg = messageEvent;

SessionCommandJson objCommandJson = new SessionCommandJson();
final FileTransferObjectServer fileObj = new FileTransferObjectServer();

JsonReader reader = new JsonReader(new StringReader(msg));
try {
reader.beginObject();
while (reader.hasNext()) {
String tagName = reader.nextName();
int msg_id;
if (tagName.equals("msg_id")){
msg_id = reader.nextInt();
if (msg_id == 257){
// 处理会话
objCommandJson.msg_id = msg_id;
 
} else if (msg_id == 1285){
//客户端获取请求获取文件
fileObj.msg_id = msg_id;
fileObj.token = mTokenNumber;

}  else if (msg_id == 1286){

if (msg.contains(".jpg")){
RemoteFile obj = (RemoteFile) GsonDeal.getGsonObjectFromString(msg, RemoteFile.class);
String fileNamePath = obj.param;
iDownLoaderListenning.onDownLoader(CollectorPath.DEFALUT_PATH_STRING + CollectorPath.PHOTO_STRING, fileNamePath);


new Thread(){

@Override
public void run() {
// TODO Auto-generated method stub
try {
sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();


}

if (msg.contains(".mp4") || msg.contains(".3gp")){
RemoteFile obj = (RemoteFile) GsonDeal.getGsonObjectFromString(msg, RemoteFile.class);
String fileNamePath = obj.param;
iDownLoaderListenning.onDownLoader(CollectorPath.DEFALUT_PATH_STRING + CollectorPath.VIDEO_STRING, fileNamePath);

}
// end
}else {
dealOtherCommand(ctx, msg_id, reader);
}
   
} else if (tagName.equals("token")){
int token = reader.nextInt();
objCommandJson.param = token;
objCommandJson.rval = 0;

String strJson = GsonDeal.getStringFromJsonObject(objCommandJson);
if (i == 0){
writeToClient(ctx, strJson);
i++;
}

} else if (tagName.equals("param") && msg.contains("1285") && !msg.contains(".txt")){// 只能进行图片或者视频的下载
fileObj.param = reader.nextString();
if (fileObj.param != null || fileObj.param.equals("")){
// 进行文件的判断处理(照片,视频)
File file = null;
String filePath = "";
String fileName = "";
if (fileObj.param.contains(".jpg")){
filePath = CollectorPath.DEFALUT_PATH_STRING + CollectorPath.PHOTO_STRING;
fileName = fileObj.param;
file = new File(filePath + fileName);
} else if (fileObj.param.contains(".mp4") || fileObj.param.contains(".3gp")){

filePath = CollectorPath.DEFALUT_PATH_STRING + CollectorPath.VIDEO_STRING;
fileName = fileObj.param;
file = new File(filePath + fileObj.param);
} else {
file = new File(CollectorPath.DEFALUT_PATH_STRING);
}


if (file.exists() && file.isFile()){
if (file.length() == 0){
fileObj.size = -1;//该文件大小为0
fileObj.rval = -1;
} else{
fileObj.size = file.length();
fileObj.rval = 1;
}

String jsonContent = GsonDeal.getStringFromJsonObject(fileObj);
writeToClient(ctx, jsonContent);



} else {
fileObj.rval = -2;//文件不存在
fileObj.size = -2;
String jsonContent = GsonDeal.getStringFromJsonObject(fileObj);
writeToClient(ctx, jsonContent);
}
} else {

}


} else if(tagName.equals("param") && msg.contains("1285") && msg.contains(".txt")){// 确认文本文件可以下载

if (msg.contains("photo")){
iDownLoaderListenning.onDownLoader(CollectorPath.DEFALUT_PATH_PHOTO_STRING);


}
  
if (msg.contains("video")){
iDownLoaderListenning.onDownLoader(CollectorPath.DEFALUT_PATH_VIDEO_STRING);
}


}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
reader.endObject();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

private void dealOtherCommand(ChannelHandlerContext ctx, int msg_id, JsonReader reader) throws IOException{
if (msg_id == 134217745){
//处理图片文本
RemoteFile objFileTxt = new RemoteFile();
objFileTxt.param = "";
objFileTxt.type = "photo";
objFileTxt.msg_id = msg_id;
objFileTxt.token = mTokenNumber;
objFileTxt.size = ReadAndWriteFile.getFileSize("photo.txt");// 值为-1时表示文件不存在
String strJson = GsonDeal.getStringFromJsonObject(objFileTxt);
writeToClient(ctx, strJson);

} else if (msg_id == 134217746){
//处理视频文本
RemoteFile objFileTxt = new RemoteFile();
objFileTxt.type = "video";
objFileTxt.param = "";
objFileTxt.msg_id = msg_id;
objFileTxt.token = mTokenNumber;
objFileTxt.size = ReadAndWriteFile.getFileSize("video.txt");// 值为-1时表示文件不存在
String strJson = GsonDeal.getStringFromJsonObject(objFileTxt);
writeToClient(ctx, strJson);


} else if (msg_id == 769){
//用户拍照,完成的时候给客户端返回
System.out.println("---------------用户拍照命令,服务端已接收,暂时不需要给用户返回信息----------");

//发送广播,进行采集器的拍照行为

} else if (msg_id == 513){
//用户开始录像,完成的时候给客户端返回msg_id = 513
System.out.println("-------------------------");
System.out.println("---------------用户录像命令,服务端已接收,暂时不需要给用户返回信息----------");

//发送广播,进行采集器的录像行为


} else if (msg_id == 514){
//用户停止录像,完成的时候给客户端返回
System.out.println("---------用户停止录像命令,服务端已接收,暂时不需要给用户返回信息----------------");


} else if (msg_id == 134217744){
//正式传输图片文本文件
iDownLoaderListenning.onDownLoader(CollectorPath.DEFALUT_PATH_PHOTO_STRING);

} else if (msg_id == 134217747){
//正式传输视频文本文件
iDownLoaderListenning.onDownLoader(CollectorPath.DEFALUT_PATH_VIDEO_STRING);
}

}



private void writeToClient(ChannelHandlerContext ctx, final String jsonContent){
System.out.println("writeToClient------jsonContent = " + jsonContent);
final ChannelHandlerContext channelHandler = ctx;
new Thread(){
public void run(){
if (channel != null){
   channelHandler.getChannel().write(jsonContent);
System.out.println("jsonContent");
} else {
instance = new SocketCommandServer();
}
}
}.start();
}
}
    
    private static int mTokenNumber;
    // 设置会话Token
  public static void setJsonToken(int iToken) {
  mTokenNumber = iToken;
  }


}
    
当中涉及到的json数据处理采用Gson架包,具体使用方法可参考网络相关资料或者查看本博客最后给出的资源链接地址下载学习。
     封转类:
package com.aprkuatang.netty.socketserver;


import com.google.gson.Gson;
import com.google.gson.JsonElement;


/**
 * JSON
 * @author KUATANG
 * 20160415
 *
 */
public class GsonDeal {
/**
* 根据对象生成JSON字符串
* @param obj
* @return
*/
public static String getStringFromJsonObject(Object obj){
Gson gson = new Gson();
Object object = obj;
return gson.toJson(object);
}

/**
* 生成JSON对象。
* @param str
* @param classOfT
* @return
*/
public static Object getGsonObjectFromString(String str, Class<?> classOfT){
Gson gson = new Gson();
return gson.fromJson(str, classOfT);
}

/**
* 根据JSON元素生成字符串。
* @param jsonElement
* @return
*/
public static String jsonStringFroamJsonElement(JsonElement jsonElement){
Gson gson = new Gson();
return gson.toJson(jsonElement);
}


}



对文本文件的操作封装类,包括读写,按行解析:


public class ReadAndWriteFile {

public static String getFileNameByDate(int typeTxt){
//图片文件名时间
Date currementDate = new Date();
SimpleDateFormat format  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String forwardDate = format.format(currementDate);
if (typeTxt == TypeTxt.type_txt_photo){
forwardDate = forwardDate + ".jpg";
}
if (typeTxt == TypeTxt.type_txt_video){
forwardDate = forwardDate + ".3gp";
}
return forwardDate;
}



public static boolean writePhotoPathToTxtFile(String fileName){

boolean isSuccess = true;
String content = "\r" + fileName + "\r\n";

File file = new File(CollectorPath.DEFALUT_PATH_PHOTO_STRING);
if (!file.exists() && !file.isFile()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file, true);
fileOutputStream.write(content.getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return isSuccess ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return isSuccess ;
} finally{
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return isSuccess ;
}
}

return isSuccess = true;
}

    public static boolean writeVideoPathToTxtFile(String fileName){

boolean isSuccess = true;
String content = "\r" + fileName + "\r\n";

File file = new File(CollectorPath.DEFALUT_PATH_VIDEO_STRING);
if (!file.exists() && !file.isFile()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file, true);
fileOutputStream.write(content.getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return isSuccess ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return isSuccess ;
} finally{
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return isSuccess ;
}
}

return isSuccess = true;
}

/**
*  获取文本内容
* @param strFilePath
* @return
*/
public static String ReadTxtFile1(String strFilePath) {
String path = strFilePath;
StringBuffer strFileContent = new StringBuffer();
final int READ_BUF_SIZE = 10240;
char[] buffer = new char[READ_BUF_SIZE];
// 打开文件
File file = new File(path);
// 如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory()) {
return null;
} else {
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(
instream);
BufferedReader buffreader = new BufferedReader(inputreader);
int len;
while ((len = buffreader.read(buffer)) != -1) {
strFileContent.append(new String(buffer, 0, len));
}
instream.close();
}
} catch (java.io.FileNotFoundException e) {
} catch (IOException e) {
}
}
return strFileContent.toString();
}

/** 获取文件的大小 **/
public static long getFileSize(String pathFileName){
String path = CollectorPath.DEFALUT_PATH_STRING + pathFileName;

File file = new File(path);
if (file.exists() && file.isFile()){
return file.length();
}
return -1;
}

/*** 
* 解析文本内容,引用需根据需求修改
* @param filePath
*/
public static void parseRecordFile1(String filePath) {
String recordContext = ReadTxtFile(filePath);

if (recordContext != null) {
final String[] fileContentArray = recordContext.split("\n");
if (filePath.contains("photo")) {

for (int i = fileContentArray.length - 1; i >= 0; i--) {
String fileName = fileContentArray[i];
if (fileName.equals(""))
continue;
Map<String, Object> map = new HashMap<String, Object>();
fileName = fileName.replace("\r","");
map.put("fileName", fileName);

}


}


}
}

/*-----------------20160512----------查找文本文件---------------- */

public static String ReadTxtFile(String strFilePath) {
String path = strFilePath;
StringBuffer strFileContent = new StringBuffer();
final int READ_BUF_SIZE = 10240;
char[] buffer = new char[READ_BUF_SIZE];


File file = new File(path);
if (!file.exists())
return null;


if (file.isDirectory()) {
return null;
} else {
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(
instream);
BufferedReader buffreader = new BufferedReader(inputreader);
int len;
while ((len = buffreader.read(buffer)) != -1) {
strFileContent.append(new String(buffer, 0, len));
}
instream.close();
}
} catch (java.io.FileNotFoundException e) {
} catch (IOException e) {
}
}
return strFileContent.toString();
}// end 
/*----------------------20160512------author:aprtang----------------------------*/
/*** 
* 解析文件文本
* @param filePath
*/
public static ArrayList<String> parseRecordFile(String filePath) {
ArrayList<String> nameList = new ArrayList<String>();

String recordContext = ReadTxtFile(filePath);

if (recordContext != null) {
final String[] fileContentArray = recordContext.split("\n");
if (filePath.contains("photo")) {

for (int i = fileContentArray.length - 1; i >= 0; i--) {
String fileName = fileContentArray[i];
if (fileName.equals(""))
continue;
Map<String, Object> map = new HashMap<String, Object>();
fileName = fileName.replace("\r","");
System.out.println("------ReadAndWriteFile------fileName ----> " + fileName);
map.put("fileName", fileName);
nameList.add(fileName);
}
}
}
return nameList;
}
/*- --------------------------------------------------------*/

public interface TypeTxt{
int type_txt_photo = 1;
int type_txt_video = 2;
}


}


调用:
package com.aprkuatang.netty.socketserver;


import com.aprkuatang.netty.socketfileserver.CollectorPath;
import com.aprkuatang.netty.socketfileserver.ReadAndWriteFile;
import com.aprkuatang.netty.socketfileserver.ReadAndWriteFile.TypeTxt;
import com.aprkuatang.netty.socketfileserver.SocketFileServer;
/**
 * Netty服务端
 * @author KUATANG
 *
 */
public class Main {

public static void main(String args[]){

ReadAndWriteFile.parseRecordFile(CollectorPath.DEFALUT_PATH_PHOTO_STRING);

String fileName = ReadAndWriteFile.getFileNameByDate(TypeTxt.type_txt_photo);
boolean isSuccess = ReadAndWriteFile.writePhotoPathToTxtFile(fileName);
System.out.println("isSuccess = " + isSuccess);
String fileName1 = ReadAndWriteFile.getFileNameByDate(TypeTxt.type_txt_video);
boolean isSuccess1 = ReadAndWriteFile.writeVideoPathToTxtFile(fileName1);
System.out.println("isSuccess = " + isSuccess1);


long i = ReadAndWriteFile.getFileSize("photo.txt");
System.out.println(i);


SocketFileServer.getInstance();
// 开启服务
SocketCommandServer.getInstance();
}


}



   


下载完整代码链接地址:http://download.csdn.net/detail/tangzhide/9646535


请注意本代码需要结合客户端代码使用,方能正确看出传输效果,由于是使用回调进行两个服务的通信,
而不是客户端发起请求服务端进行处理方式,您可能会发现,使用本人后续提供的客户端代码运行项目时,
只能进行一次文件的传输而抛出服务端断开连接的异常,这就是没有请求,想要直接使用服务端进行主观传输造成的问题,
Socket也需要客户端做请求。修改方案和客户端代码将会在后续的博客和资源中给出。


本次代码出上述阐述问题为正确运行代码,可作为学习Netty的参考或者修改后直接使用到项目。






0 0
原创粉丝点击