public class FileServerHandler extends SimpleChannelInboundHandler<String> {
@Override
public void messageReceived(ChannelHandlerContext ctx, String fileName) throws Exception {
RandomAccessFile file = new RandomAccessFile(fileName, "r");
ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
}
} extends SimpleChannelInboundHandler<String>)public class SimpleServer {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
new ServerBootstrap().group(group)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new ObjectEncoder());
pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
pipeline.addLast(new SimpleChannelInboundHandler<RandomAccessFile>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, RandomAccessFile randomAccessFile) throws Exception {
System.out.println("GOD DAMN, I GOT IT");
}
});
}
})
.bind("localhost", 8080)
.sync()
.channel()
.closeFuture()
.syncUninterruptibly();
} finally {
group.shutdownGracefully();
}
}
}public class Client {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
new Bootstrap().group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new ObjectEncoder());
pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
pipeline.addLast(new SimpleChannelInboundHandler<RandomAccessFile>() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
RandomAccessFile file = new RandomAccessFile("C:/Users/Панк/Desktop/screen.png", "r");
ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
System.out.println("here active");
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, RandomAccessFile randomAccessFile) throws Exception {
System.out.println("client got message");
}
});
}
})
.connect("localhost", 8080)
.sync()
.channel()
.closeFuture()
.sync();
} finally {
group.shutdownGracefully();
}
}
} во-первых, метода messageReceived, мы не можем его переписать
channelRead0во-вторых, я не понимаю, почему мы в генерик кидаем строку
Вероятно у меня стоят неверные декодеры и энкодеры
pipeline.addLast(new SimpleChannelInboundHandler<DefaultFileRegion>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, DefaultFileRegion defaultFileRegion ) throws Exception {
System.out.println("GOD DAMN, I GOT A FILE");
}
});DefaultFileRegionDecoder, а без них работать ничего не будет