使用netty的第一个Hello World

时间:2022-12-01 11:47:19

server端

package com.netty.test;
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;

public class DiscardServer {

private static int port = 8080;

private static String tcpIp = "localhost";

public static void run(){
EventLoopGroup bossGroup = new NioEventLoopGroup();//用于处理服务器端,接收客户端链接
EventLoopGroup workerGroup = new NioEventLoopGroup();//进行网络通信(读写)
try {
ServerBootstrap b = new ServerBootstrap();//辅助工具类,用于服务器通道的一系列配置
//绑定两个线程组
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)//指定nio模式
.childHandler(new ChannelInitializer<SocketChannel>() {//配置具体的数据处理方式,处理数据用io模式,该地方使用io包

@Override
protected void initChannel(SocketChannel socketChannel)
throws Exception {
socketChannel.pipeline().addLast(new ServerHandler());
}

}).option(ChannelOption.SO_BACKLOG, 128)//设置tcp缓冲区
.option(ChannelOption.SO_SNDBUF, 32 * 1024) //设置发送数据缓冲区
.option(ChannelOption.SO_RCVBUF, 32 * 1024)//设置接收数据的缓冲区
.childOption(ChannelOption.SO_KEEPALIVE, true);//保持链接
//绑定端口
ChannelFuture future = b.bind(tcpIp, port).sync()/*b.bind(port).sync()*/;
future.channel().closeFuture().sync();
} catch (Exception e) {
System.out.println("产生了异常;异常是" + e.getMessage());
}finally{
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}

}
public static void main(String[] args) {
run();
}

}

ServerHandler类

package com.netty.test;

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

/*
* 服务器接收和返回数据
*/
public class ServerHandler extends ChannelInboundHandlerAdapter {

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

// 接收客户端的消息
ByteBuf buf = (ByteBuf)msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
String request = new String(data, "utf-8");
System.out.println("Server: " + request);
// 写给客户端
ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));
//.addListener(ChannelFutureListener.CLOSE);

}

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

}

Client端

package com.netty.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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 {

private static int port = 8080;

private static String tcpIp = "localhost";

public static void main(String[] args) {
EventLoopGroup worGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {

@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());

}

});
try {
ChannelFuture future = bootstrap.connect(tcpIp, port).sync();
// 给服务器发送消息
future.channel().writeAndFlush(Unpooled.copiedBuffer("Hello World!".getBytes()));
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("绑定ip和端口时抛出异常,异常是" + e.getMessage());
e.printStackTrace();
} finally {
worGroup.shutdownGracefully();
}


}

}

ClientHandler类

package com.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
/*
* 接收服务器返回的消息
*/
public class ClientHandler extends ChannelInboundHandlerAdapter{

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
try {
ByteBuf buf = (ByteBuf)msg;
byte[] data = new byte[buf.readableBytes()];
buf.readBytes(data);
System.out.println("Client : " + new String(data).trim());
} finally {
ReferenceCountUtil.release(msg);
}

}

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

}