Netty 是一个基于NIO的客户、服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。

  Netty简单来说就是socket通讯,支持多协议的通讯

对 创建 netty 的过程作了详细的解析

1、简单创建一个Netty服务器

package com.netty.test;

import java.net.InetAddress;

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.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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; /**
* Netty4 服务端代码
*
*/
public class HelloWorldServer { public static void main(String[] args) {
// EventLoop 代替原来的 ChannelFactory
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();        //创建 一个netty 服务器
// server端采用简洁的连写方式,client端才用分段普通写法。
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)              // 指定channel[通道]类型
.childHandler(new ChannelInitializer<SocketChannel>() {    // 指定Handler [操纵者]
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 以("\n")为结尾分割的 解码器
ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); // 字符串 解码 和 编码 默认的 StringDecoder 字符串形式输出
ch.pipeline().addLast("decoder", new StringDecoder());
ch.pipeline().addLast("encoder", new StringEncoder()); ch.pipeline().addLast(new HelloServerHandler());     // 添加自己的对 上传数据的处理
}
}).option(ChannelOption.SO_KEEPALIVE, true);
       ChannelFuture f = serverBootstrap.bind(8000).sync();           // 绑定 8000 端口
f.channel().closeFuture().sync(); }
catch (InterruptedException e) { } finally {
workerGroup.shutdownGracefully(); // 销毁 netty
bossGroup.shutdownGracefully();
}
} /**
* 自己对 处理数据
*
* @author flm
* 2017年11月10日
*/
private static class HelloServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 收到消息直接打印输出
System.out.println(ctx.channel().remoteAddress() + " Say : " + msg); // 返回客户端消息 - 我已经接收到了你的消息
ctx.writeAndFlush("server Received your message !\n");
} /*
*
* 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
*
* channelActive 和 channelInActive 在后面的内容中讲述,这里先不做详细的描述
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !"); ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n"); //回复 super.channelActive(ctx);
}
}

2、netty 客户端 创建

package com.netty.test;

import java.net.InetSocketAddress;
import java.util.Date; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; /**
* Netty4 客户端代码
*
*/
public class HelloWorldClient { public static void main(String args[]) { // Bootstrap,且构造函数变化很大,这里用无参构造。
Bootstrap bootstrap = new Bootstrap();
// 指定channel[通道]类型
bootstrap.channel(NioSocketChannel.class);
// 指定Handler [操纵者]
bootstrap.handler(new ChannelInitializer<Channel>() { @Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline(); /*
* 这个地方的 必须和服务端对应上。否则无法正常解码和编码
*
*/
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder()); // 客户端的逻辑,自己对数据处理
pipeline.addLast(new HelloClientHandler());
}
});
// 指定EventLoopGroup [事件 组]
bootstrap.group(new NioEventLoopGroup()); // 连接到本地的8000端口的服务端
bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000)); } /**
* 客户端的逻辑,自己对数据处理
*
* @author flm
* 2017年11月10日
*/
private static class HelloClientHandler extends ChannelInboundHandlerAdapter { /*
* 监听 服务器 发送来的数据
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("Server say : " + msg.toString()); } /*
* 启动客户端 时触发
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client active ");
ctx.writeAndFlush("我是 client " + new Date() + "\n");
super.channelActive(ctx);
} /*
* 关闭 客户端 触发
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client close ");
super.channelInactive(ctx);
}
}
}

Netty——简单创建服务器、客户端通讯的更多相关文章

  1. 运用socket实现简单的服务器客户端交互

    Socket解释: 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意 ...

  2. 【Netty】Netty简介及服务器客户端简单开发流程

    什么是Netty Netty是一个基于Java NIO的编写客服端服务器的框架,是一个异步事件框架. 官网https://netty.io/ 为什么选择Netty 由于JAVA NIO编写服务器的过程 ...

  3. 【Echo】实验 -- 实现 C/C++下TCP, 服务器/客户端 通讯

    本次实验利用TCP/IP, 语言环境为 C/C++ 利用套接字Socket编程,实现Server/CLient 之间简单的通讯. 结果应为类似所示: 下面贴上代码(参考参考...) Server 部分 ...

  4. 【Echo】实验 -- 实现 C/C++下UDP, 服务器/客户端 通讯

    本次实验利用UDP协议, 语言环境为 C/C++ 利用套接字Socket编程,实现Server/CLient 之间简单的通讯. 结果应为类似所示: 下面贴上代码(参考参考...) Server 部分: ...

  5. Windows Socket 编程_ 简单的服务器/客户端程序

    转载自:http://blog.csdn.net/neicole/article/details/7459021 一.程序运行效果图 二.程序源代码 三.程序设计相关基础知识 1.计算机网络    2 ...

  6. 简单实现服务器/客户端的c代码

    #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> ...

  7. Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端

    Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端用AsynchronousServerS ...

  8. Netty创建服务器与客户端

    Netty 创建Server服务端 Netty创建全部都是实现自AbstractBootstrap.客户端的是Bootstrap,服务端的则是ServerBootstrap. 创建一个 HelloSe ...

  9. macos下简单的socket服务器+客户端

    TCP客户端服务器编程模型: 服务器: 调用socket函数创建套接字 调用bind绑定本地IP和端口 调用listen启动监听(准备好接收客户端链接的队列) 调用accept从已连接队列中提取第一个 ...

随机推荐

  1. 小米2017秋招真题——电话号码分身问题(Java版)

    原题描述如下: 通过对各个数字对应的英文单词的分析,可以发现一些规律: 字母Z为0独占,字母W为2独占,字母U为4独占,字母X为6独占,字母G为8独占: 在过滤一遍0.2.4.6.8后,字母O为1独占 ...

  2. Spring事务源码阅读笔记

    1. 背景 本文主要介绍Spring声明式事务的实现原理及源码.对一些工作中的案例与事务源码中的参数进行总结. 2. 基本概念 2.1 基本名词解释 名词 概念 PlatformTransaction ...

  3. hdu 5954 -- Do not pour out(积分+二分)

    题目链接 Problem Description You have got a cylindrical cup. Its bottom diameter is 2 units and its heig ...

  4. HIVE---基于Hadoop的数据仓库工具讲解

    Hadoop: Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用来开发分布式程序.充分利用集群的威力进行高速运算和存储.Hadoop实现了一个分布式文件系统(Hadoop Dist ...

  5. Linq常用List操作总结,ForEach、分页、交并集、去重、SelectMany等

    /* 以下围绕Person类实现,Person类只有Name和Age两个属性 一.List<T>排序 1.1 List<T>提供了很多排序方法,sort(),Orderby() ...

  6. django中间件Middleware

    熟悉web开发的同学对hook钩子肯定不陌生,通过钩子可以方便的实现一些触发和回调,并且做一些过滤和拦截. django中的中间件(middleware)就是类似钩子的一种存在.下面我们来介绍一下,并 ...

  7. 初学者易上手的SSH-struts2 04值栈与ognl表达式

    什么是值栈?struts2里面本身提供的一种存储机制,类似于域对象,值栈,可以存值和取值.,特点:先进后出.如果将它当做一个容器的话,而这个容器有两个元素,那么最上面的元素叫做栈顶元素,也就是所说的压 ...

  8. Python开篇

    一:Python的前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为 ...

  9. wpf C# 数据库 c/s 个人信息管理 wpf局域网通信

    系统功能基本要求 wpf局域网通信 WPF跨线程访问线程安全的数据如解决该类型的CollectionView不支持从调度程序线程以外的线程对其SourceCollection 读取信息null 读取发 ...

  10. 简说chart2.4的应用,以及Uncaught ReferenceError : require is not defined的解决

    51呢最近在学习chart.js,然后呢就照着中文的帮助文档来然后就一直出Uncaught ReferenceError : require is not defined的问题查了挺多才知道是帮助文档 ...