案例說明:客戶端發(fā)送一個信息到服務器端麸澜,服務器端將信息原樣返回
0 添加maven依賴
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.21.Final</version>
</dependency>
</dependencies>
1. ServerHandler
《Netty in Action》中介紹過暮的,我們不需要使每一個inboundChannel繼承于ChannelInboundHandler件甥,這樣會需要我們實現(xiàn)ChannelInboundHandler中的所有接口杭煎,在一般的channel中我們沒有必要這樣做逮光,這樣只會增加我們的額外的工作量,我們只需要繼承ChannelInboundHandlerAdapter栖秕,繼承它的適配就可以了春塌,我們需要實現(xiàn)幾個特別重要的方法,例如讀取的方法channelRead和異常處理的方法exceptionCaught簇捍,源碼如下:
package com.ly.netty.hello;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class HelloWorldServerHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Hello");
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("server channelRead..");
System.out.println(ctx.channel().remoteAddress()+ msg.toString());
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
2. Server
接下來我們就要寫Netty的服務器端了只壳。寫server端需要注意,就是需要關閉連接暑塑,釋放線程資源吼句,源碼如下:
package com.ly.netty.hello;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class HelloWorldServer {
private int port;
public HelloWorldServer(int port) {
this.port = port;
}
public void start(){
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap sbs = new ServerBootstrap();
sbs.group(bossGroup,workerGroup);
sbs.channel(NioServerSocketChannel.class);
sbs.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("decoder", new StringDecoder());
ch.pipeline().addLast("encoder", new StringEncoder());
ch.pipeline().addLast(new HelloWorldServerHandler());
};
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 綁定端口,開始接收進來的連接
ChannelFuture future = sbs.bind(port).sync();
System.out.println("Server start listen at " + port );
future.channel().closeFuture().sync();
} catch (Exception e) {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new HelloWorldServer(port).start();
}
}
3. ClientHandler
如法炮制事格,客戶端的handler惕艳,我們依舊命名為HelloWorldClientHandler况毅,也是繼承于ChannelInboundHandlerAdapter。
package com.ly.netty.hello;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class HelloWorldClientHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("HelloWorldClientHandler Active");
ctx.fireChannelActive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("HelloWorldClientHandler read Message:"+msg);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("HelloWorldClientHandler inActive!");
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
4. Client
完整的代碼如下:
package com.ly.netty.hello;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class HelloWorldClient {
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8080"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
public static void main(String[] args) throws Exception {
initChannel();
}
public static void initChannel() throws InterruptedException{
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("decoder", new StringDecoder());
p.addLast("encoder", new StringEncoder());
p.addLast(new HelloWorldClientHandler());
}
});
// SocketAddress socketAddress = InetSocketAddress.createUnresolved(address.getHost(), address.getPort());
SocketAddress socketAddress = new InetSocketAddress(HOST, PORT);
ChannelFuture future = b.connect(socketAddress).sync();
future.channel().writeAndFlush("hello world");
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
Netty的服務器端和客戶端就搭建完尔艇。我們做到了客戶端發(fā)送信息,服務器端接收且把收到的信息原樣返回給客戶端了么鹤。
我的Github項目终娃,歡迎大家指導!Watch蒸甜!Star棠耕!Fork! Thanks!
GitHub-Netty-demo-server
GitHub-Netty-demo-client