package com.snailteam.netty; import io.netty.bootstrap.ServerBootstrap; 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.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * 服务端Bootstrap * @author * */ public class NServer { static final int PORT = 8080; public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { /** Inbound: 1 ->2 ->3 ->n 顺序处理 Outbound: n ->n-1 ->n-2 .. ->1 逆序处理 */ //new LengthFieldBasedFrameDecoder(1024*8*20, 0, 4,0,4) 最大1024*8*20位为接收数据包,从0,长4Byte是数据宽度,然后从0,长4Byte剔除后的byte数据包,传送 到后面的handler链处理 ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG),new LengthFieldBasedFrameDecoder(1024*8*20, 0, 4,0,4), new NServerHandler()); } }); // Bind and start to accept incoming connections. b.bind(PORT).sync().channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
package com.snailteam.netty; import java.nio.charset.Charset; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class NServerHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { String str = msg.toString(Charset.forName("UTF-8")); System.out.println("[ok]" +str ); str = "辛苦了"+str.substring(str.lastIndexOf(',')+1); ctx.writeAndFlush(Unpooled.wrappedBuffer(str.getBytes())); } }
package com.snailteam.netty; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; 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.LengthFieldPrepender; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * 客户端Bootstrap * */ public class Nclient { public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { //LengthFieldPrepender 把发送的数据前加4Byte存储数据宽度,发送。 ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG),new LengthFieldPrepender(4), new NclientHandler()); } }); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 20; i++) { sb.append("中华人民共和国" + i + ","); } // Bind and start to accept incoming connections. Channel con = b.connect("localhost", NServer.PORT).sync().channel(); for (int i = 0; i < 900; i++) { String str = sb.toString() + i; con.writeAndFlush(Unpooled.wrappedBuffer(str.getBytes())).sync().get(); System.out.println(i); } con.close().sync();//异步退出 } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } }
package com.snailteam.netty; import java.nio.charset.Charset; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class NclientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println(msg.toString(Charset.forName("UTF-8"))); } }
package com.snailteam.netty; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; public class FrameDecoder extends ByteToMessageDecoder{ int lengthFeildLength = 4; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { Object decoded = decode(ctx, in); if (decoded != null) { out.add(decoded); } } private Object decode(ChannelHandlerContext ctx, ByteBuf in) { if(in.readableBytes()<lengthFeildLength)return null;// int index = in.readerIndex(); int len = in.readInt();//解析次数包中对象的大小 if(in.readableBytes()<len){//数据包的内容不全 in.readerIndex(index);//重置readerIndex return null; } return in.readRetainedSlice(len);//截取完整的一个转码对象。 } }
pom
<dependency> <groupId>io.netty</groupId> <artifactId>netty-example</artifactId> <version>4.1.6.Final</version> <exclusions> <exclusion> <artifactId>netty-tcnative</artifactId> <groupId>io.netty</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-tcnative</artifactId> <version>1.1.33.Fork23</version> <classifier>windows-x86_64</classifier> </dependency>
相关推荐
使用的是 netty3,用于 客户端 服务端 长连接收发信息的例子
通过netty4实现的简单的服务端与客户端的源代码,采用IntelliJ IDEA 2018.1.3开发工具,该例子可以帮助你入门netty框架。
自己收藏的netty使用例子,有需要的可以下载
netty实现websocket,客户端向服务端发送信息,然后服务器返回当前时间。连接成功后也可向客户端主动发信息。
netty4小例子 客户端+服务端+日志 只是小例子
例子的内容是:服务端启动,客户端启动,客户端连接服务器后服务器发一个Message的对象给客户端,客户端接受并打印Message里边的内容。编解码的处理为:消息长度[int] + 消息内容[byte[]]。心跳设置的是读写空闲都是10...
感觉netty5.0 的例子 网上好少..要么照搬官方例子..要么就是老版本的过期..自己也是刚入门,找资料做了个例子 客户端与服务端通讯
LineBaseFrameDecoder 换行符解码器 DelimiterBaseFrameDecoder 定界符解码器
用Netty5写一个简单的服务端和客户端,通过这个示例可以起到快速入门的效果,下载完成后,可运行4_Netty5_Hello模块代码,其中包括客户端单连接和多连接的例子
C# winform Socket 即时通讯完整例子,服务端和客户端都有,带详细注释,带详细注释,带详细注释,特别适合新手学习
本源代码例子实现了Socket服务端和客户端,以及Http服务端和客户端;采用了Netty框架,实现SSL/TLS支持。
定义消息协议通讯 ,及心跳检测例子,包含客户端和服务端代码
Netty5入门3个简单例子,让你快速入门,一个服务端、客户端,以及一个参考的网站地址;Netty5是个优秀稳定高效的java服务器框架,特别适用于java游戏服务器快速开发!
•每个客户端仅能使用一个长连接连接服务端。 •客户端与服务端通讯之前需要在服务端配置用户名密码。 •每次建立连接需要发送登录信息,用于确定消息与客户端关系。 •通讯链路需考虑心跳保持,心跳间隔4分钟。 •...
根据网上和书籍的netty入门例子,编写一个具有交互功能的netty时间和系统版本通信通信框架,源码中包括服务端和客户端两个部分,对netty初学者有一定的指导作用。
这个socket通信比较直观,比较容易看懂,实现了Java中的socket的通信问题。是Java网络编程的一个比较不错的例子!
阻塞IO模式就是一个客户端连接到服务端,服务端就为每个新的客户端 Socket 创建一个新的 Thread。 Netty的书我帮你看!---什么是Netty 什么是Socket?Socket就是你想用Java代码API去组织数据,指定协议去通讯,很烦!...
Netty入门-第一个例子HelloWorld,包含服务端和客户端代码。说明:所有代码属于从互联网、书本拷贝或者加工处理,能满足运行要求只用于交流和学习用 ———————————————— 版权声明:本文为CSDN博主「m0...
《Linux多线程服务端编程:使用muduo C++网络库》主要讲述采用现代C++在x86-64 Linux上编写多线程TCP网络服务程序的主流常规技术,重点讲解一种适应性较强的多线程服务器的编程模型,即one loop per thread。...
熔断0.0.9快照重新本地服务缓存实现添加服务端定时推送数据到admin支持自动发现本地IP支持无序启动服务添加客户端定时ping功能0.0.8快照客户端断线自动重连允许跳过启动绑定服务允许自定义异常支持方法等级的高可用...