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

本文档展示了如何使用Netty搭建一个服务端,该服务端专注于文件处理和JSON数据传输。通过创建一个单例模式的SocketFileServer类,配置Netty的ChannelPipeline并实现文件传输和JSON编码解码。服务端使用NioServerSocketChannelFactory创建通道,监听8787端口,并自定义FileTransferChannelHandler来处理连接、关闭、异常和消息接收事件。此外,还涉及了Gson库处理JSON数据的方法。
摘要由CSDN通过智能技术生成


使用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;
}
});
   
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值