先上代码,一睹为快!
import java.nio.charset.Charset;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class NettySocketServer {
private int port = 9999;
public void runServer() {
NioEventLoopGroup boss = new NioEventLoopGroup();//接收线程
NioEventLoopGroup worker = new NioEventLoopGroup();//工作线程
try {
ServerBootstrap server = new ServerBootstrap();
server.group(boss, worker);//设置线程
server.channel(NioServerSocketChannel.class);//设置服务类型 socket服务
server.handler(new LoggingHandler(LogLevel.INFO));//设置日志处理器
server.childHandler(new ChannelInitializer<SocketChannel>() {//增加初始化
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipe = ch.pipeline();
pipe.addLast(new StringEncoder(Charset.forName("UTF-8")));//出站编码处理
pipe.addLast(new StringDecoder(Charset.forName("UTF-8")));//按照客户端的编码格式,将入参转为字符串,即下边的inbound handler里的msg为String类型
pipe.addLast(new MyInServerHandler0());
}
});
server.option(ChannelOption.SO_BACKLOG, 128);//官网示例
server.childOption(ChannelOption.SO_KEEPALIVE, true);//官网示例
//绑定端口并且添加监听和异步启动
ChannelFuture future = server.bind(port).sync();//启动
future.channel().closeFuture().sync();//启动
} catch (Exception e) {
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public class MyInServerHandler0 extends ChannelInboundHandlerAdapter {
Log log = LogFactory.getLog(MyInServerHandler0.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String data = (String) msg;
String ret = "我给你返回了";
//返回值必须都得转成ByteBuf类型,或者在初始化的地方增加对应的出站编码器 比如StringEncoder
//ctx.writeAndFlush(Unpooled.copiedBuffer(ret.getBytes("UTF-8")));
log.info("MyInServerHandler0.channelRead");
ctx.writeAndFlush(ret);
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.info("MyInServerHandler0.exceptionCaught");
ctx.writeAndFlush(cause.getMessage());
ctx.close();
}
}
public static void main(String[] args) {
NettySocketServer serv = new NettySocketServer();
serv.runServer();
}
}