您的位置:首页 > 其它

Netty4框架的初步使用

2017-06-02 16:14 239 查看

Netty4框架的初步使用

Netty4的基本概念网上有很多,这里就不多说,这仅仅只是一个小例子。

功能模块分三部分:

1、Handler,消息处理

2、Client,客户端

3、Server,服务端

结构目录:



代码如下:

公用的Handler

package com.zmm.netty4introduction.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public abstract class CommonHandler extends SimpleChannelInboundHandler<String> {

@Override
protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
System.out.println("---" + ctx.channel().remoteAddress() + " 收到消息 = "+s);
}

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("---" + ctx.channel().remoteAddress() + " 活跃中...");
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("---" + ctx.channel().remoteAddress() + " 闲置中...");
}

}


Client端

ClientHandler类:目前未做其他功能,继承公共Handler即可

package com.zmm.netty4introduction.client;

import com.zmm.netty4introduction.handler.CommonHandler;

public class ClientHandler extends CommonHandler {
}


Client类:

package com.zmm.netty4introduction.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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;

public class Client {

private static final String host = "127.0.0.1";
private static final int port = 7878;

public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {

ChannelPipeline p = socketChannel.pipeline();

//String的编码器和解码器,netty提供,要和Server一致
p.addLast(new StringDecoder());
p.addLast(new StringEncoder());

p.addLast(new ClientHandler());
}
});

// 连接服务端
Channel ch = bootstrap.connect(host, port).sync().channel();

System.out.println("---Server connect Success---");

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
System.out.println("请输入:");
String line = in.readLine();
if (line == null) {
continue;
}

ch.writeAndFlush(line + "\r\n");
}
}catch (Exception e){
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
}


服务端

ServerHandler类:这里做了一个处理,当收到客户端数据后,返回一条消息

package com.zmm.netty4introduction.server;

import com.zmm.netty4introduction.handler.CommonHandler;

import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends CommonHandler {

private int count = 1;

@Override
protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
System.out.println("---Server 收到客户端消息 = "+s);

ctx.writeAndFlush("服务端返回信息"+count++);

}
}


Server类:

package com.zmm.netty4introduction.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Server {

private static final int port = 7878;

public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {

ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {

ChannelPipeline p = socketChannel.pipeline();

//String的编码器和解码器,netty提供,要和Client一致
p.addLast(new StringDecoder());
p.addLast(new StringEncoder());

p.addLast(new ServerHandler());
}

});

// 服务器绑定端口监听
Channel ch = bootstrap.bind(port).sync().channel();

System.out.println("---Server Start---");

ch.closeFuture().sync();

} catch (Exception e){
throw new RuntimeException(e);
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}


注意事项:

1、因为未做特殊处理,所以要先运行Server,再运行Client。

2、若要先运行Client也可以,可以看下一篇,接着会写一篇Netty4长连接的文章,里面会用Msgpack传递数据,其中会包括Tcp长连接、断开重连、心跳监测、Msgpack的编码和解码等。

GitHub:Netty4Introduction

(直接在AndroidStudio上运行即可)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: