<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.38.Final</version>
</dependency>
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* Netty 服务端
*/
public class NettyServerListenerSimple {
/**
* 创建bootstrap
*/
private static final ServerBootstrap serverBootstrap = new ServerBootstrap();
/**
* Worker
*/
private static final EventLoopGroup work = new NioEventLoopGroup();
/**
* 端口号
*/
private int port = getPort();
/**
* 关闭服务器方法
*/
public void close() {
System.out.println("关闭服务器....");
//优雅退出
work.shutdownGracefully();
}
/**
* 开启及服务线程
*/
public void start() {
serverBootstrap.group(work)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO));
try {
//设置事件处理
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ServerChannelHandlerSimple());
}
});
System.out.println("netty服务器在[" + port + "]端口启动监听");
ChannelFuture f = serverBootstrap.bind(port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("[出现异常] 释放资源");
work.shutdownGracefully();
}
}
private static int getPort() {
Double port = (Math.random() + 1) * 10000;
return port.intValue();
}
public static void main(String[] args) {
NettyServerListenerSimple nsl = new NettyServerListenerSimple();
nsl.start();
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;
/**
* 服务端的通道适配器
*/
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("error.");
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 具体处理客户端的数据信息
System.out.println("receive message. ");
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println(rev);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Charset.forName("GBK"));
} catch (Exception e) {
System.out.println("trans bytes to string error. ");
e.printStackTrace();
return null;
}
}
}
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ServerChannelHandlerSimple());
}
});
System.out.println("netty服务器在[" + port + "]端口启动监听");
ChannelFuture f = serverBootstrap.bind(port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("[出现异常] 释放资源");
work.shutdownGracefully();
}
}
private static int getPort() {
Double port = (Math.random() + 1) * 10000;
return port.intValue();
}
public static void main(String[] args) {
NettyServerListenerSimple nsl = new NettyServerListenerSimple();
nsl.start();
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;
/**
* 服务端的通道适配器
*/
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("error.");
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 具体处理客户端的数据信息
System.out.println("receive message. ");
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println(rev);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Charset.forName("GBK"));
} catch (Exception e) {
System.out.println("trans bytes to string error. ");
e.printStackTrace();
return null;
}
}
}
部署实现自己的netty 客户端
package com.youkeda.test.netty.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("error.");
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 具体处理客户端的数据信息
System.out.println("receive message. ");
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println(rev);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Charset.forName("GBK"));
} catch (Exception e) {
System.out.println("trans bytes to string error. ");
e.printStackTrace();
return null;
}
}
}
package com.youkeda.test.netty.server;
import com.youkeda.test.netty.handler.ServerChannelHandlerSimple;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class NettyServerListenerSimple {
/**
* 创建bootstrap
*/
private static final ServerBootstrap serverBootstrap = new ServerBootstrap();
/**
* Worker
*/
private static final EventLoopGroup work = new NioEventLoopGroup();
/**
* 端口号
*/
private int port = getPort();
/**
* 关闭服务器方法
*/
public void close() {
System.out.println("关闭服务器....");
//优雅退出
work.shutdownGracefully();
}
/**
* 开启及服务线程
*/
public void start() {
serverBootstrap.group(work)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO));
try {
//设置事件处理
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ServerChannelHandlerSimple());
}
});
System.out.println("netty服务器在[" + port + "]端口启动监听");
ChannelFuture f = serverBootstrap.bind(port);
f.channel().closeFuture();
} catch (Exception e) {
System.out.println("[出现异常] 释放资源");
} finally {
close();
}
}
private static int getPort() {
Double port = (Math.random() + 1) * 10000;
return port.intValue();
}
public static void main(String[] args) {
NettyServerListenerSimple nsl = new NettyServerListenerSimple();
nsl.start();
}
}