由于dubbo默认使用的是netty3进行通信的,这里简单的列出一个netty3通信的例子。

一 server端

1 Server

 package com.hulk.netty.server;

 import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder; import java.net.InetSocketAddress;
import java.util.concurrent.Executors; public class Server {
public void start(){
ChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),//boss线程池
Executors.newCachedThreadPool(),//worker线程池
8//worker线程数
);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
/**
* 对于每一个连接channel, server都会调用PipelineFactory为该连接创建一个ChannelPipline
*/
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ServerLogicHandler());
return pipeline;
}
}); Channel channel = bootstrap.bind(new InetSocketAddress("127.0.0.1", 8080));
System.out.println("server start success!");
} public static void main(String[] args) throws InterruptedException {
Server server = new Server();
server.start();
Thread.sleep(Integer.MAX_VALUE);
}
}

步骤:

  • 首先创建了NioServerSocketChannelFactory:创建boss线程池,创建worker线程池以及worker线程数。(boss线程数默认为1个)
  • 创建ServerBootstrap server端启动辅助类
  • 为ServerBootstrap设置ChannelPipelineFactory工厂,并为ChannelPipelineFactory将来创建出的ChannelPipeline设置编码器/解码器/事件处理器
  • 使用ServerBootstrap绑定监听地址和端口

2 事件处理器ServerLogicHandler

 package com.hulk.netty.server;

 import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler; public class ServerLogicHandler extends SimpleChannelHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
System.out.println("连接成功, channel: " + e.getChannel().toString());
} @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
String msg = (String) e.getMessage();
System.out.println("接收到了client的消息, msg: " + msg); Channel channel = e.getChannel();
String str = "hi, client"; channel.write(str);//写消息发给client端
System.out.println("服务端发送数据: " + str + "完成");
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
e.getCause().printStackTrace();
e.getChannel().close();
}
}

说明:

  • 监听与客户端连接成功事件
  • 监听接收到来自客户端的消息,之后写回给客户端消息
  • 捕捉异常事件

二 client端

1 Client

 package com.hulk.netty.client;

 import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder; import java.net.InetSocketAddress;
import java.util.concurrent.Executors; public class Client {
public static void main(String[] args) {
ChannelFactory factory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool(),
8
);
ClientBootstrap bootstrap = new ClientBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ClientLogicHandler());
return pipeline;
}
}); bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
System.out.println("client start success!");
}
}

步骤:(与Server几乎相同)

  • 首先创建了NioClientSocketChannelFactory:创建boss线程池,创建worker线程池以及worker线程数。(boss线程数默认为1个)
  • 创建ClientBootstrap client端启动辅助类
  • 为ClientBootstrap设置ChannelPipelineFactory工厂,并为ChannelPipelineFactory将来创建出的ChannelPipeline设置编码器/解码器/事件处理器
  • 使用ClientBootstrap连接Server端监听的地址和端口

2 ClientLogicHandler

 package com.hulk.netty.client;

 import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.WriteCompletionEvent; public class ClientLogicHandler extends SimpleChannelHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
System.out.println("客户端连接成功!");
String str = "hi server!";
e.getChannel().write(str);//异步
} @Override
public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception {
System.out.println("客户端写消息完成");
} @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
String msg = (String) e.getMessage();
System.out.println("客户端接收到消息, msg: " + msg);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
e.getCause().printStackTrace();
e.getChannel().close();
}
}

说明:

  • 监听与服务端连接成功事件,连接成功后,写消息给服务端
  • 监听向服务端写消息完成的事件
  • 监听接收到来自服务端的消息
  • 捕捉异常事件

这就是一个简单的netty3通信的例子,关于netty,后续会读源码。

7.3 netty3基本使用的更多相关文章

  1. netty3升netty4一失眼成千古恨

    老项目是netty3的,本来想直接改到netty5,但是netty5居然是只支持jdk1.7,很奇怪jdk1.6和jdk1.8都不行..为了兼容jdk1.6加上netty4本来和netty5就差别不大 ...

  2. 使用Netty3或Netty4发布Http协议服务

    现在是2018年1月11日18:12分,已经是下班时间了,小Alan今天给大家简单的介绍一下Netty,让大家以后在使用到Netty的时候能够有一定的了解和基础,这样深入学习Netty以及以后灵活应用 ...

  3. nio之netty3的应用

    1.netty3是nio的封装版本.在使用上面比nio的直接使用更好.nio简单使用都是单线程的方式(比如:一个服务员服务很多客户),但是netty3的方式不一样的是,引入线程池的方式来实现服务的通信 ...

  4. 蓝萝卜blu netty3升netty4

    老项目是netty3的,本来想直接改到netty5,但是netty5居然是只支持jdk1.7,很奇怪jdk1.6和jdk1.8都不行..为了兼容jdk1.6加上netty4本来和netty5就差别不大 ...

  5. 以http server为例简要分析netty3实现

    概要 最近看了点netty3实现.从webbit项目作为口子.webbit项目是一个基于netty3做的http与websocket server.后面还会继续看下netty4,netty4有很多改进 ...

  6. Netty3 源代码分析 - NIO server绑定过程分析

    Netty3 源代码分析 - NIO server绑定过程分析      一个框架封装的越好,越利于我们高速的coding.可是却掩盖了非常多的细节和原理.可是源代码可以揭示一切. 服务器端代码在指定 ...

  7. Netty3:分隔符和定长解码器

    回顾TCP粘包/拆包问题解决方案 上文详细说了TCP粘包/拆包问题产生的原因及解决方式,并以LineBasedFrameDecoder为例演示了粘包/拆包问题的实际解决方案,本文再介绍两种粘包/拆包问 ...

  8. 在netty3.x中存在两种线程:boss线程和worker线程。

    在netty 3.x 中存在两种线程:boss线程和worker线程.

  9. netty-3.客户端与服务端通信

    (原) 第三篇,客户端与服务端通信 以下例子逻辑: 如果客户端连上服务端,服务端控制台就显示,XXX个客户端地址连接上线. 第一个客户端连接成功后,客户端控制台不显示信息,再有其它客户端再连接上线,则 ...

随机推荐

  1. ElasticSearch 入门总结

    ElasticSearch 入门 本篇为 ElasticSearch 入门学习总结笔记,课程视频地址:ElasticSearch 入门 一.ElasticSearch 简介 1.1.什么是Elasti ...

  2. 洛谷.4721.[模板]分治FFT(NTT)

    题目链接 换一下形式:\[f_i=\sum_{j=0}^{i-1}f_jg_{i-j}\] 然后就是分治FFT模板了\[f_{i,i\in[mid+1,r]}=\sum_{j=l}^{mid}f_jg ...

  3. 【bfs】BZOJ1102- [POI2007]山峰和山谷Grz

    最后刷个水,睡觉去.Bless All! [题目大意] 给定一个地图,为FGD想要旅行的区域,地图被分为n*n的网格,每个格子(i,j) 的高度w(i,j)是给定的.若两个格子有公共顶点,那么他们就是 ...

  4. [CF580E]Kefa and Watch

    题目大意: 维护一个由'0'~'9'构成的字符串,支持以下两种操作: 1.将指定区间内的所有字符修改为同一指定字符. 2.询问$x$是否为指定区间内的循环节. 思路: 建立一棵线段树,维护每个子串的哈 ...

  5. KVM源代码解读:linux-3.17.4\include\uapi\linux\kvm.h

    #ifndef __LINUX_KVM_H #define __LINUX_KVM_H /* * Userspace interface for /dev/kvm - kernel based vir ...

  6. 使用 IntraWeb (22) - 基本控件之 TIWCalendar

    TIWCalendar: 日历控件, 继承于 TIWCustomGrid, 所以它和 TIWGrid 共同属性特多. 它的 Cell 是 TIWCalendarCell 对象, 直接从 TIWGrid ...

  7. 正余弦信号的DFT频谱分析

    一般的,对正余弦信号进行採样并DFT运算,画出频谱图,会发现频谱并不干净.这样的现象称为频谱泄漏.由于DFT运算仅仅能是有限序列,突然的截断产生了泄漏. 会有这种特殊情况.当採样截取的刚好是整数个周期 ...

  8. SPI SWD Protocol Implement

    //================================================================================= // ARM SWD Mode ...

  9. 关于bootstrap的treeview不显示多选(复选框)的问题,以及联动选择的问题,外加多选后取值

    最近做项目用到了treeview.因为涉及到多选的问题,很是棘手,于是乎,我决定查看原生JS,探个究竟.需要引用官方的bootstrap-treeview.js都知道吧,对于所需要引用的,我就不多说了 ...

  10. mozilla/rr 调试

    http://rr-project.org/ https://github.com/mozilla/rr