基于netty的echo server和echo client

既然学了netty自然需要实验下,自然自己就简单实验下。
这个是简版的,所以比较粗糙。



package study.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {

private static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);

private int port;

public EchoServer(int port) {

this.port = port;
}

public static void main(String... args) {

EchoServer echoServer = new EchoServer(12345);
echoServer.start();
}

public void start() {

NioEventLoopGroup bossGroup = new NioEventLoopGroup(),
workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(port)
.childHandler(new ChannelInitializer<Channel>() {

@Override
protected void initChannel(Channel ch) throws Exception {

ch.pipeline().addLast(new EchoServerHandler());
}
});

ChannelFuture f = bootstrap.bind().sync();
System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
f.channel().closeFuture().sync();
} catch (InterruptedException e) {

LOGGER.error(e.getMessage());
} finally {

try {
workerGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {

LOGGER.error(e.getMessage());
}
}
}
}




[color=orange][size=medium]不过没其他原因的话,最好还是用SimpleChannelInboundHandler吧,毕竟池化的bytebuf虽然性能好,但是自己手动维护难免错误。[/size][/color]

package study.netty;

import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

private static final Logger LOGGER = LoggerFactory.getLogger(EchoServerHandler.class);

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

super.channelActive(ctx);
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

ByteBuf byteBuf = (ByteBuf) msg;
LOGGER.info("echo server receive msg:{}", byteBuf.toString(StandardCharsets.UTF_8));
ctx.write(msg);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {

ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}




package study.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class EchoClient {

private final Logger logger = LoggerFactory.getLogger(getClass());

private static String host = "127.0.0.1";
private static int port = 12345;

public static void main(String[] args) {

EchoClient client = new EchoClient();
client.start();
}

public void start() {

NioEventLoopGroup nelg = new NioEventLoopGroup();
try {

Bootstrap bootstrap = new Bootstrap();
bootstrap.group(nelg)
.channel(NioSocketChannel.class)
.remoteAddress(host, port)
.handler(new ChannelInitializer<Channel>() {

@Override
protected void initChannel(Channel ch) throws Exception {

ch.pipeline().addLast(new EchoClientHandler());
}
});

ChannelFuture future = bootstrap.connect().sync();
future.channel().closeFuture().sync();

} catch (InterruptedException e) {

e.printStackTrace();
} finally {

try {
nelg.shutdownGracefully().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}



package study.netty;

import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

private final Logger logger = LoggerFactory.getLogger(getClass());

@Override
public void channelActive(ChannelHandlerContext ctx) {

ctx.writeAndFlush(Unpooled.copiedBuffer("client short msg", StandardCharsets.UTF_8));
}

@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

logger.info("client received:{}", msg.toString(StandardCharsets.UTF_8));
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

logger.error(cause.getMessage());
ctx.close();
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值