简单的介绍一些服务端代码的编写顺序。
1.得到 ServerBootstrap的对象,用来监听客户端
ServerBootstrap serverBootstrap = new ServerBootstrap();
2.创建两个线程池
EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup();
boss用来对端口的监听,worker对数据进行处理
3.设置工厂
serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class);
4.设置,可以理解为netty3中的管道
serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { /** * 将“上传下载”数据装饰成String类型 */ channel.pipeline().addLast(new StringDecoder()); channel.pipeline().addLast(new StringEncoder()); // 要处理的Handler channel.pipeline().addLast(new ServerHandler2()); } });
5.设置TCP参数
serverBootstrap.option(ChannelOption.SO_BACKLOG, 2048);// serverSocketchannel的设置,链接缓冲池的大小 serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);// socketchannel的设置,维持链接的活跃,清除死链接 serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);// socketchannel的设置,关闭延迟发送
6.绑定端口
ChannelFuture future = serverBootstrap.bind(new InetSocketAddress( 9090));
7.(等待)关闭客户端
Channel channel = future.channel(); channel.closeFuture().sync();
完整代码如下:
服务端:
package com.netty5.server; import java.net.InetSocketAddress; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; /** * @author Chalmers 2016年2月20日 下午7:52:49 */ public class NettyServer2 { public static void main(String[] args) { // 得到ServerBootstrap对象 ServerBootstrap serverBootstrap = new ServerBootstrap(); // 创建线程池 EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { // 类似于Netty3中的工厂 serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class); // 类似于Netty3中的管道 serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { /** * 将“上传下载”数据装饰成String类型 */ channel.pipeline().addLast(new StringDecoder()); channel.pipeline().addLast(new StringEncoder()); // 要处理的Handler channel.pipeline().addLast(new ServerHandler2()); } }); // 设置参数,TCP参数 serverBootstrap.option(ChannelOption.SO_BACKLOG, 2048);// serverSocketchannel的设置,链接缓冲池的大小 serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);// socketchannel的设置,维持链接的活跃,清除死链接 serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);// socketchannel的设置,关闭延迟发送 // 绑定端口,并且返回ChannelFuture对象 ChannelFuture future = serverBootstrap.bind(new InetSocketAddress( 9090)); System.out.println("启动服务器..."); // 等待客户端的关闭 Channel channel = future.channel(); // 要记得是closeFuture(),作用是等待服务端的关闭 channel.closeFuture().sync(); // 该条语句不会输出,原因:上面没有关闭... // System.out.println("客户端已经关闭..."); } catch (Exception e) { e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } } class ServerHandler2 extends SimpleChannelInboundHandler<String> { @Override protected void messageReceived(ChannelHandlerContext arg0, String arg1) throws Exception { // 输出接收到的数据 System.out.println(arg1); // 向客户端发送数据 arg0.channel().writeAndFlush("hi"); } /** * */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); System.out.println("channelActive"); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); System.out.println("channelInactive"); } }
客户端:
package com.netty.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; /** * @author Chalmers 2016年2月20日 下午8:31:25 */ public class Client { public static void main(String[] args) { Bootstrap bootstrap = new Bootstrap(); EventLoopGroup worker = new NioEventLoopGroup(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(worker); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline().addLast(new StringEncoder()); channel.pipeline().addLast(new StringDecoder()); channel.pipeline().addLast(new ClientHandler()); } }); ChannelFuture future = bootstrap.connect("127.0.0.1", 9090); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.print("输入: "); try { String line = br.readLine(); future.channel().writeAndFlush(line); } catch (IOException e) { e.printStackTrace(); } } } } class ClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void messageReceived(ChannelHandlerContext arg0, String arg1) throws Exception { System.out.println("收到服务端发送的消息..." + arg1); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // TODO Auto-generated method stub super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // TODO Auto-generated method stub super.channelInactive(ctx); } }
因为netty5与netty3的差别挺大,所以注意区分开。
http://moonmonster.iteye.com/blog/2278672
当然,因为本人水平有限,所以更详细的解释可见
netty权威指南作者的博客
相关推荐
利用idea,构建的maven项目,用idea打开即可测试运行,实现了netty的服务段和客户端,利用netty实现服务端和客户端的通信demo.
Netty服务端与客户端,数据的发送与接收 使用:先运行TimeServer,在运行TimeClient。成功连接后,服务器发送一个时间给客户端。输出到客户端控制台 4.第三个示例 com.user_1 Netty将java对象作为数据的发送与...
11.实战:构建客户端与服务端 Pipeline 18 12.实战:拆包粘包理论与解决方案 20 13.ChannelHandler的生命周期 21 14.实战:使用ChannelHandler的热插拔实现客户端身份校验 23 15.实战:群聊消息的收发及Netty性能优化 23...
54_Netty服务端初始化过程与反射在其中的应用分析 55_Netty提供的Future与ChannelFuture优势分析与源码讲解 56_Netty服务器地址绑定底层源码分析 57_Reactor模式透彻理解及其在Netty中的应用 58_Reactor模式与Netty...
第54讲:Netty服务端初始化过程与反射在其中的应用分析 第55讲:Netty提供的Future与ChannelFuture优势分析与源码讲解 第56讲:Netty服务器地址绑定底层源码分析 第57讲:Reactor模式透彻理解及其在Netty中的应用...
52_NioEventLoopGroup源码分析与线程数设定 53_Netty对Executor的实现机制源码分析 54_Netty服务端初始化过程与反射在其中的应用分析 55_Netty提供的Future与ChannelFuture优势分析与源码讲解 56_Netty服务器地址...
使用Netty构建一个基于WebSocket的聊天室服务器。可以使多个用户使用浏览器可以同时进行相互通信。 程序逻辑: 1、客户端发送一个消息; 2、该消息将被广播到所有其他连接的客户端 服务端启动后,浏览器输入...
解决方案: “ J-Reactive-8583” ISO8583客户端和服务器基于进行编码/解码, 出色的异步消息传递框架构建。 它根据Apache License 2.0分发。 支持的功能 客户端和服务器端点。 Java 11+ 使用库支持ISO8583消息。 ...
WebSocket是H5新增的协议,用于构建浏览器和服务器之间的不受限的长连接的通信模式,不再局限于请求/响应式的模型,服务端可以主动推送消息给客户端,(游戏有某个玩家得奖了的弹幕)基于这个特性我们可以构建我们的实时的...
Gretty 是一个简单的 Web 框架,用于构建 Web 服务端和客户端,基于 Netty 开发,支持 NIO 风格的 HTTP 服务器,异步 HTTP 客户端,支持 WebSocket 的服务器和客户端。 标签:Gretty
Tethys是采用开发的IM服务器,致力于服务端响应式技术开发推广与研究,可快速构建功能完备,高效且可定制化的IM服务。 特色 免费的 高效 可靠的 功能 用户认证 私人聊天 群组聊天 消息存储 容器部署 好友关系 离线...
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。 ...
本项目是作者小傅哥使用技术栈JavaFx , Netty4.x , SpringBoot , Mysql等,构建的仿制桌面版微信聊天工程实现通信核心功能。如果本项目能为您提供帮助,请给予支持(关注,点赞,分享)! 作者:小傅哥,Java开发...
在Producer方面,分为普通发送者和事务消息发送者,其中普通发送者构建Netty客户端向Broker发送消息,而事务消息发送者还需要构建Netty服务端以供Broker回查本地事务状态。消息存储方面,探讨了Broker如何存储...
本项目为 Friendship_Killer 的服务端程序,该服务器由 Java 编写,数据库使用 MySQL,数据库管理使用 JDBC,底层网络框架为 Netty。其中,client 为 socket 通信的客户端。后续有配套博客,敬请关注
该项目实现了联机版坦克大战,项目包括客户端与服务端 项目使用技术: 使用Netty实现客户端和服务端之间的通讯 使用Marshalling作为编解码技术 游戏界面使用java自带的swing与awt进行编写 使用Spring的依赖注入与...
Leo-IM,开源好用的IM。 Leo-IM是基于Java语言、Netty框架、Vue+Element-UI开发的轻量级IM,服务端可独立运行...构建与部署 安装netty-rest-server到本地仓库 mvn install:install-file -Dfile=netty-rest-server-1.0.
WebSocket4J 是一个用 Java 实现的 WebSocket 协议的类库,可使用 Java 来构建交互式 Web 应用。WebSocket4J 并未实现客户端通讯协议,所以不能用它来连接 WebSocket 服务器。 Struts验证码插件 JCaptcha4Struts2 ...
《Linux多线程服务端编程:使用muduo C++网络库》主要讲述采用现代C++在x86-64 Linux上编写多线程TCP网络服务程序的主流常规技术,重点讲解一种适应性较强的多线程服务器的编程模型,即one loop per thread。...
netty实现的轻量级Socks5版本,支持使用SSL加密传输。 特性 支持启用SSL *使用SSL加密传输,防止中间人拦截篡改原始数据 简单易用 *只需少量配置即可启动一个属于自己的Socks5服务 轻量级实现 *可以在该源代码基础上...