title: netty的學(xué)習(xí)
tags: [netty]
最近寫android的tcp通信,用來(lái)傳輸文件慈俯,用原生的寫太麻煩了鳍侣,還有開(kāi)線程互相監(jiān)聽(tīng),一堆操作比較繁瑣辆脸,了解到netty比較好用,封裝的簡(jiǎn)單螃诅,就用了這個(gè)來(lái)寫啡氢。
用的netty版本 'io.netty:netty-all:4.1.6.Final' ,
先注冊(cè)一個(gè)線程池 EventLoopGroup group =new NioEventLoopGroup();放在全局,
這里是服務(wù)端术裸,只寫了接收信息
// MainApplication 里面的 因?yàn)檫@里是寫的android所以放到了MainApplication里面注冊(cè)的
EventLoopGroup group = MainApplication.getGroup();
ChannelFuture cf = MainApplication.getCf();
//
public static ChannelFuture cf =MainApplication.getCf();
public static EventLoopGroup group = MainApplication.getGroup();
public static void start(){
try {
Bootstrap b = new Bootstrap();
b.group(group) // 注冊(cè)線程池
.channel(NioSocketChannel.class)
// 設(shè)置緩存區(qū)大小
// .option(ChannelOption.RCVBUF_ALLOCATOR,
// new AdaptiveRecvByteBufAllocator(64,1024,204800))
// 使用NioSocketChannel來(lái)作為連接用的channel類
.remoteAddress(new InetSocketAddress(host, port))
// 綁定連接端口和host信息
.handler(new ChannelInitializer<SocketChannel>() { // 綁定連接初始化器
@Override
protected void initChannel(SocketChannel ch) throws Exception {
Log.d(TAG, "initChannel: 正在連接中...");
// 設(shè)置好可以打印傳輸?shù)牧餍畔? // ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
// 實(shí)例化一個(gè)處理類倘是,傳一些需要用到的參數(shù)參數(shù)
ch.pipeline().addLast(new ClientHandle(filePath, data, promise, host, port));
ch.pipeline().addLast(new ByteArrayEncoder());
ch.pipeline().addLast(new ChunkedWriteHandler());
}
});
// System.out.println("服務(wù)端連接成功..");
cf = b.connect().sync(); // 異步連接服務(wù)器
cf.channel().closeFuture().sync();// 異步等待關(guān)閉連接channel
}
finally {
// 最后執(zhí)行完可以釋放線程池,如果有多次操作就沒(méi)必要釋放了袭艺,
// group.shutdownGracefully().sync(); // 釋放線程池資源
}
}
public class ClientHandle extends SimpleChannelInboundHandler<ByteBuf> {
int fileSize = 0;
private String TAG ="LoggingHandler";
private DataOutputStream out;
public ClientHandle(String filePath, Map data, String host, int port) throws FileNotFoundException {
super();
// 其他一些參數(shù)無(wú)視掉
Log.e(TAG, "ClientHandle: "+"進(jìn)來(lái)了ClientHandle");
this.filePath = filePath;
// 這里被實(shí)例化后就創(chuàng)建文件流搀崭。然后在下面寫入文件
out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(filePath)));
}
/**
* 向服務(wù)端發(fā)送數(shù)據(jù)
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Log.d(TAG, "客戶端與服務(wù)端通道-開(kāi)啟:" + ctx.channel().localAddress() +
// "channelActive");
Log.d(TAG, "channelActive: ");
ctx.writeAndFlush(); // 可以發(fā)送流信息
}
/**
* channelInactive
*
* channel 通道 Inactive 不活躍的
*
* 當(dāng)客戶端主動(dòng)斷開(kāi)服務(wù)端的鏈接后,這個(gè)通道就是不活躍的。也就是說(shuō)客戶端與服務(wù)端的關(guān)閉了通信通道并且不可
以傳輸數(shù)據(jù)
*
*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Log.d(TAG, "客戶端與服務(wù)端通道-關(guān)閉:" + ctx.channel().localAddress() +
"channelInactive");
}
// 這里讀取數(shù)據(jù)瘤睹,每次流進(jìn)來(lái)就會(huì)觸發(fā)此函數(shù)
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
// 這里msg當(dāng)然需要轉(zhuǎn)化下的升敲,轉(zhuǎn)換格式根據(jù)服務(wù)端的編碼轉(zhuǎn)換
out.write(msg)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws
Exception {
ctx.close();
cause.printStackTrace();
Log.d(TAG, "異常退出");
}
}
客戶端
這里可能有點(diǎn)不是很搭,但是畢竟好配合我們的業(yè)務(wù)轰传,因?yàn)榭蛻舳耸前惭b在一個(gè)小板子上面的驴党,板子存儲(chǔ)能力很弱,所有就選擇了node來(lái)做服務(wù)端來(lái)發(fā)送消息获茬。
node tcp發(fā)送消息
var net = require('net');
net.createServer(function(socket){
// socket.setKeepAlive(true, 1000);
socket.on('data', function(data){
transferUtils.resolveAndSendFile(data, socket);
});
socket.on('close',function () {
console.log("client close");
});
socket.on('error', function(err){
console.log("Socket transmit error!", err);
})
// 監(jiān)聽(tīng)15000端口
}).listen(15000, "0.0.0.0");