FileClient.java
2.3 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
*
*/
package com.waylau.netty.demo.file;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
* 说明:文件客户端
*
* @author <a href="http://www.waylau.com">waylau.com</a> 2015年11月6日
*/
public class FileClient {
private String host;
private int port;
private String dest; // 接收到文件存放的路径
/**
*
*/
public FileClient(String host, int port, String dest) {
this.host = host;
this.port = port;
this.dest = dest;
}
public void run() throws InterruptedException, IOException {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("encoder",
new StringEncoder(CharsetUtil.UTF_8));
ch.pipeline().addLast("decoder",
new StringDecoder(CharsetUtil.UTF_8));
ch.pipeline().addLast(new FileClientHandler(dest));
}
});
// 启动客户端
ChannelFuture f = b.connect(host, port).sync(); // (5)
Channel channel = f.channel();
// 控制台输入请求的文件路径
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
while (true) {
channel.writeAndFlush(in.readLine() + "\r\n");
}
// 等待连接关闭
// f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException, IOException {
new FileClient("localhost", 8082, "D:/reciveFile.txt").run();
}
}