MINA网络通信框架
- - 淘宝网通用产品团队博客Apache MINA 2是一个开发高性能和高可伸缩性网络应用程序的网络应用框架. 它提供了一个抽象的事件驱动的异步API,可以使用TCP/IP、UDP/IP、串口和虚拟机内部的管道等传输方式. Apache MINA 2可以作为开发网络应用程序的一个良好基础. Mina 的API 将真正的网络通信与我们的应用程序隔离开来,你只需要关心你要发送、.
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha2</version> </dependency>
import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; 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.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.timeout.IdleStateHandler; public class NettyServerBootstrap { private static Logger logger = Logger.getLogger(NettyServerBootstrap.class); private int port; public NettyServerBootstrap(int port) { this.port = port; bind(); } private void bind() { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //连接数 bootstrap.option(ChannelOption.TCP_NODELAY, true); //不延迟,消息立即发送 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //长连接 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline p = socketChannel.pipeline(); p.addLast(new NettyServerHandler()); } }); ChannelFuture f = bootstrap.bind(port).sync(); if (f.isSuccess()) { logger.debug("启动Netty服务成功,端口号:" + this.port); } // 关闭连接 f.channel().closeFuture().sync(); } catch (Exception e) { logger.error("启动Netty服务异常,异常信息:" + e.getMessage()); e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { NettyServerBootstrap server= new NettyServerBootstrap(9999); } }
import java.io.UnsupportedEncodingException; import com.datong.base.module.netty.common.Constant; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class NettyServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf); System.out.println("服务器接收到消息:" + recieved); try { ctx.writeAndFlush(getSendByteBuf("APPLE")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /* * 从ByteBuf中获取信息 使用UTF-8编码返回 */ private String getMessage(ByteBuf buf) { byte[] con = new byte[buf.readableBytes()]; buf.readBytes(con); try { return new String(con, Constant.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException { byte[] req = message.getBytes("UTF-8"); ByteBuf pingMessage = Unpooled.buffer(); pingMessage.writeBytes(req); return pingMessage; } }
import java.util.concurrent.TimeUnit; import io.netty.bootstrap.Bootstrap; 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.NioSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.timeout.IdleStateHandler; public class NettyClient { /* * 服务器端口号 */ private int port; /* * 服务器IP */ private String host; public NettyClientBootstrap(int port, String host) throws InterruptedException { this.port = port; this.host = host; start(); } private void start() throws InterruptedException { EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.group(eventLoopGroup); bootstrap.remoteAddress(host, port); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler()); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); if (future.isSuccess()) { socketChannel = (SocketChannel) future.channel(); System.out.println("----------------connect server success----------------"); } future.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { NettyClient client = new NettyClient(9999, "localhost"); } }
import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; import com.netty.common.NettyStartRunable; import com.netty.common.ProxyPool; import com.netty.util.JsonUtil; import net.sf.json.JSONObject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class NettyClientHandler extends ChannelHandlerAdapter { private ByteBuf firstMessage; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { byte[] data = "服务器,给我一个APPLE".getBytes(); firstMessage=Unpooled.buffer(); firstMessage.writeBytes(data); ctx.writeAndFlush(firstMessage); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; String rev = getMessage(bug); System.out.println("客户端收到服务器数据:" + rev); } private String getMessage(ByteBuf buf) { byte[] con = new byte[buf.readableBytes()]; buf.readBytes(con); try { return new String(con, Constant.UTF8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }