sever相关代码
EchoServer.java
public class EchoServer {
private int port;
public EchoServer(int port){
this.port = port;
}
public static void main(String[] args) {
// if (args.length != -1) {
// System.err.println("Usage:"+EchoServer.class.getSimpleName()+"<port>");
// }
// int port = Integer.parseInt(args[0]);
int port = 8099;
new EchoServer(port).start();
}
//引导服务启动步骤
private void start() {
final EchoServerHandler serverHandler = new EchoServerHandler();
//1、创建一个NioEventLoopGroup
EventLoopGroup group = new NioEventLoopGroup();
try {
//2、创建ServerBootstrap并引导绑定相关配置
ServerBootstrap b = new ServerBootstrap();
b.group(group)//2.1、绑定group
.channel(NioServerSocketChannel.class)//2.2、绑定Channel
.localAddress(new InetSocketAddress(port))//2.3、绑定本地端口和ip
.childHandler(new ChannelInitializer<SocketChannel>() {//2.4、绑定childHandler
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
group.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
EchoServerHandler .java
@Sharable//标示一个channelhandler可以被多个channel共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter{
/**
* 对于每一个传入的消息都要调用
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf)msg;
System.out.println("server receiverd:"+in.toString(CharsetUtil.UTF_8));
ctx.write(in);//将接收到的消息写给发送者,而不是冲刷出站消息
}
/**
* 通知ChannelInboundHandler最后一次对channelRead()的调用是当前批量读取中的最后一条消息。
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);//将未决消息冲刷到远程节点,并关闭该Channel
}
/**
* 在读取操作期间,有异常抛出时会调用。
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();//打印异常
ctx.close();//关闭Channel
}
}
client的相关代码
EchoClient .java
public class EchoClient {
private final String host;
private final int port;
public EchoClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start(){
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();//创建bootStrap
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
group.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// if (args.length !=2) {
// System.err.println("Usage:"+EchoClient.class.getSimpleName()+"<host><port>");
// return;
// }
String host = "127.0.0.1";
int port = 8099;
// String host = args[0];
// int port = Integer.parseInt(args[1]);
new EchoClient(host, port).start();
}
}
EchoClientHandler .java
@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
/**
* 在到服务器的连接已经建立之后将被调用
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",CharsetUtil.UTF_8));
}
/**
* 当从服务器接收到一条消息时被调用
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("client received:"+msg.toString(CharsetUtil.UTF_8));
}
/**
* 在处理过程中引发异常时调用
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}