보뇨 다이어리

Netty framework 를 이용한 텍스트 파일 교환 본문

컴퓨터 관련/Java 정보

Netty framework 를 이용한 텍스트 파일 교환

보뇨 2018. 2. 21. 15:54
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
 
/**
 * Simplistic telnet server.
 */
public final class TelnetServer {
 
    static final boolean SSL = System.getProperty("ssl"!= null;
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023"));
 
    public static void main(String[] args) throws Exception {
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }
 
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new TelnetServerInitializer(sslCtx));
 
            b.bind(PORT).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
 
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.net.InetAddress;
import java.util.Date;
 
/**
 * Handles a server-side channel.
 */
@Sharable
public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {
    int titleNum = 1;
 
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.write("ready for copy inputTextFiles !\r\n");
        ctx.flush();
    }
 
    @Override
    public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
        String response;
//        boolean close = false;
        BufferedWriter fw = new BufferedWriter(new FileWriter("txtfiles\\" + titleNum + ".txt"true));
        System.out.println(request);
     
        if ("null".equals(request.toLowerCase())) {
            response = "Have a good day!\n";
            fw.close();
            titleNum++;
        } else {
            response = "You said '" + request + "'\n";
            request = request + "\r\n";
            fw.write(request);
            fw.flush();
        }
        ctx.write(response);
    }
 
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
 
public class TelnetServerInitializer extends ChannelInitializer<SocketChannel> {
 
    private static final StringDecoder DECODER = new StringDecoder();
    private static final StringEncoder ENCODER = new StringEncoder();
 
    private static final TelnetServerHandler SERVER_HANDLER = new TelnetServerHandler();
 
    private final SslContext sslCtx;
 
    public TelnetServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }
 
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
 
        if (sslCtx != null) {
            pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        }
 
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(DECODER);
        pipeline.addLast(ENCODER);
 
        pipeline.addLast(SERVER_HANDLER);
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
 
/**
 * Simplistic telnet client.
 */
public final class TelnetClient {
 
    static final boolean SSL = System.getProperty("ssl"!= null;
    static final String HOST = System.getProperty("host""127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023"));
 
    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            sslCtx = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }
 
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            File file = new File("bin\\");
            File[] list = file.listFiles();
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new TelnetClientInitializer(sslCtx));
            Channel ch = b.connect(HOST, PORT).sync().channel();
            ChannelFuture lastWriteFuture = null;
            
            for(File f : list) {
                FileReader fr2 = new FileReader(f);
                BufferedReader in2 = new BufferedReader(fr2);
                for(;;) {
                    String line2 = in2.readLine();
                    System.out.println(line2);
                    lastWriteFuture = ch.writeAndFlush(line2 + "\r\n");
                    if(line2 == null) {
                        break;
                    }
                }
            }
            ch.closeFuture().sync();
            
            if(lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
 
/**
 * Handles a client-side channel.
 */
@Sharable
public class TelnetClientHandler extends SimpleChannelInboundHandler<String> {
 
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.err.println(msg);
    }
 
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
 
/**
 * Creates a newly configured {@link ChannelPipeline} for a new channel.
 */
public class TelnetClientInitializer extends ChannelInitializer<SocketChannel> {
 
    private static final StringDecoder DECODER = new StringDecoder();
    private static final StringEncoder ENCODER = new StringEncoder();
 
    private static final TelnetClientHandler CLIENT_HANDLER = new TelnetClientHandler();
 
    private final SslContext sslCtx;
 
    public TelnetClientInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }
 
    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
 
        if (sslCtx != null) {
            pipeline.addLast(sslCtx.newHandler(ch.alloc(), TelnetClient.HOST, TelnetClient.PORT));
        }
 
        // Add the text line codec combination first,
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(DECODER);
        pipeline.addLast(ENCODER);
 
        // and then business logic.
        pipeline.addLast(CLIENT_HANDLER);
    }
}
cs


반응형

'컴퓨터 관련 > Java 정보' 카테고리의 다른 글

Zookeeper 를 통해 간단한 서버 만들기  (0) 2018.03.11
스트림(Stream) 에 대하여 알아보자  (0) 2018.03.01
AtomicLong 클래스  (0) 2018.02.13
Jackson 예제  (0) 2018.02.11
맵(Map) 클래스  (0) 2018.02.09