package smu.gaoyi.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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.DelimiterBasedFrameDecoder;
/**
* Netty服務端
*
* @author gaoyi
*
*/
public class Server {
private void bind(int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//服務端輔助啓動類,用以降低服務端的開發複雜度
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
//實例化ServerSocketChannel
.channel(NioServerSocketChannel.class)
//設置ServerSocketChannel的TCP參數
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler());
// ChannelFuture:代表異步I/O的結果
ChannelFuture f = bootstrap.bind(port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("啓動netty服務異常");
e.printStackTrace();
} finally {
System.out.println("end");
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//handler
ByteBuf delimiter = Unpooled.copiedBuffer("<--->".getBytes());
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048,delimiter));
ch.pipeline().addLast(new ServerHandler());
}
}
public static void main(String[] args) {
int port = 8888;
new Server().bind(port);
}
}
package smu.gaoyi.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class Client {
public void connect(String host, int port) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new Client().connect("localhost", 8888);
}
}
package smu.gaoyi.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ClientHandler extends ChannelInboundHandlerAdapter{
// private final ByteBuf byteBuf;
public ClientHandler() {
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//向服務端發送數據
byte[] bytes = "i love you<--->".getBytes();
ByteBuf byteBuf = Unpooled.buffer(bytes.length);
byteBuf.writeBytes(bytes);//寫入buffer
byte[] bytes1 = "i love you1<--->".getBytes();
ByteBuf byteBuf1 = Unpooled.buffer(bytes1.length);
byteBuf1.writeBytes(bytes1);//寫入buffer
byte[] bytes2 = "i love you2<--->".getBytes();
ByteBuf byteBuf2 = Unpooled.buffer(bytes2.length);
byteBuf2.writeBytes(bytes2);//寫入buffer
ctx.writeAndFlush(byteBuf);
ctx.writeAndFlush(byteBuf1);
ctx.writeAndFlush(byteBuf2);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//讀取服務端發過來的數據
ByteBuf buf = (ByteBuf)msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String message = new String(bytes, "UTF-8");
System.out.println("客戶端收到的消息: " + message);
}
}
package smu.gaoyi.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Handles a server-side channel.
* @author yi.gao
*
*/
public class ServerHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String message = new String(bytes, "UTF-8");
System.out.println("服務端收到的消息: " + message);
//向客戶端寫數據
String response = "hello client";
ByteBuf buffer = Unpooled.copiedBuffer(response.getBytes());
ctx.write(buffer);//寫入緩衝數組
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelReadComplete...");
ctx.flush();//將緩衝區數據寫入SocketChannel
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exceptionCaught...");
}
}