第一个例子中,建立了http的服务器端,可以直接使用curl命令,或者浏览器直接访问。

在第二个例子中,建立一个netty的客户端来主动发送请求,模拟浏览器发送请求。

这里先启动服务端,再启动客户端,启动客户端后,在 channelActive 方法中,主动向服务器端发送消息,服务器端channelRead0 方法中,接收到客户端的消息后,会再向客户端返回消息。客户端channelRead0方法中接收到消息再向客户端发送消息,依次往复。

同样的,按照顺序

client

 import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; public class MyClient {
public static void main(String[] args) throws InterruptedException {
//客户端只需要一个
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try{ Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new MyClientInitlalizer());
ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); //channelFuture.channel().writeAndFlush("first msg");//发送数据,其实应该写到handler的active方法中 channelFuture.channel().closeFuture().sync(); }finally {
eventLoopGroup.shutdownGracefully();
} }
}

Initlalizer

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil; public class MyClientInitlalizer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline channelPipeline = ch.pipeline(); //添加解码器的handler
channelPipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); channelPipeline.addLast(new LengthFieldPrepender(4));
//字符串的解码器
channelPipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
//字符串的编码器
channelPipeline.addLast( new StringEncoder(CharsetUtil.UTF_8));
//自定义的处理器
channelPipeline.addLast(new MyClientHandler());
}
}

handler

 import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import java.time.LocalDateTime; public class MyClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println( ctx.channel().remoteAddress() + "," + msg);
System.out.println( "client output:" + msg); ctx.writeAndFlush("from client" + LocalDateTime.now());
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
//super.exceptionCaught(ctx, cause);
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.channel().writeAndFlush("来自客户端的问候!");//通道连接之后,发送数据
super.channelActive(ctx);
}
}

sever中的handle

server中的server代码和第一个例子类似,initlializer和client中的一致,就不贴代码了。

public class MyServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress() + "," + msg); ctx.writeAndFlush("from serevber" + UUID.randomUUID());//消息返回
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
// super.exceptionCaught(ctx, cause);
}
}

3、netty第二个例子,使用netty建立客户端,与服务端通讯的更多相关文章

  1. Netty入门之客户端与服务端通信(二)

    Netty入门之客户端与服务端通信(二) 一.简介 在上一篇博文中笔者写了关于Netty入门级的Hello World程序.书接上回,本博文是关于客户端与服务端的通信,感觉也没什么好说的了,直接上代码 ...

  2. Netty入门——客户端与服务端通信

    Netty简介Netty是一个基于JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞.基于事件驱动.高性能.高可靠性和高可定制性.换句话说,Netty是一个NIO框架,使用它可以简单快速 ...

  3. [Java]Hessian客户端和服务端代码例子

    简要说明:这是一个比较简单的hessian客户端和服务端,主要实现从客户端发送指定的数据量到服务端,然后服务端在将接收到的数据原封不动返回到客户端.设计该hessian客户端和服务端的初衷是为了做一个 ...

  4. Java基础---Java---网络编程---TCP的传输、客户端和服务端的互访、建立一个文本转换器、编写一个聊天程序

    演示TCP的传输的客户端和服务端的互访 需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息. 客户端: 1.建立Socket服务,指定要连接方朵和端口 2.获取Socket流中的输出流,将数 ...

  5. Netty实现客户端和服务端通信简单例子

    Netty是建立在NIO基础之上,Netty在NIO之上又提供了更高层次的抽象. 在Netty里面,Accept连接可以使用单独的线程池去处理,读写操作又是另外的线程池来处理. Accept连接和读写 ...

  6. 【Netty源码分析】客户端connect服务端过程

    上一篇博客[Netty源码分析]Netty服务端bind端口过程 我们介绍了服务端绑定端口的过程,这一篇博客我们介绍一下客户端连接服务端的过程. ChannelFuture future = boos ...

  7. tcp,第一个例子,客户端,服务端

    1.客户端 package cd.itcast.xieyi; import java.io.IOException; import java.io.OutputStream; import java. ...

  8. thrift例子:python客户端/java服务端

    java服务端的代码请看上文. 1.说明: 这两篇文章其实解决的问题是,当使用python去访问大数据线上集群的时候,遇到两个问题: 1)python-hadoop和python-hive相关包链接不 ...

  9. python7.3客户端、服务端的建立

    import socket #创建客户端client=socket.socket() #生成socket连接对象client.connect("localhost",6969) # ...

随机推荐

  1. 记录我的 python 学习历程-Day05 字典/字典的嵌套

    一.字典的初识 为什么要有字典 字典与列表同属容器型数据类型,同样可以存储大量的数据,但是,列表的数据关联性不强,并且查询速度比较慢,只能按照顺序存储. 什么是字典 先说一下什么叫可变与不可变的数据类 ...

  2. HDU1217-Arbitrage(乘法最短路)

    Arbitrage is the use of discrepancies in currency exchange rates to transform one unit of a currency ...

  3. Python3 并发编程1

    目录 操作系统发展 穿孔卡片 批处理 多道技术(单核) 并发与并行 进程 程序与进程 进程调度 进程的三个状态 同步和异步 阻塞与非阻塞 僵尸进程与孤儿进程 守护进程 Python中的进程操作 Pro ...

  4. 使用脚本安装 Docker

    使用脚本安装 Docker 1.使用 sudo 或 root 权限登录 Centos. 2.确保 yum 包更新到最新. $ sudo yum update 3.执行 Docker 安装脚本. $ c ...

  5. oc实现小型学生管理系统

                              首先,创建一个工程,然后加入两个cocoaclass,分别命名为Student   和 StudentSystem.   然后就可以开始写代码喽   ...

  6. angular6路由参数的传递与获取

    1.访问路由链接:/test/id 路由配置: {path: 'test/:id', component: TestComponent} html传参: <a href="javasc ...

  7. cygwin报错 /bin/bash: Operation not permitted

    如题,使用Cygwin过程中本来好好的,突然就不能登录了,每个用户登录都报错 /bin/bash: Operation not permitted.开始也以为是没有权限之类的,重装弄了很久也不行.后面 ...

  8. QQ音乐接口api,包括付费音乐、无损音乐、高品质音乐地址解析接口api

    QQ音乐网站所有音乐(包括付费.无损等版权音乐解析接口地址url). mp3 普通高品 http://dl.stream.qqmusic.qq.com/M5000012gqVh4fFvVK.mp3?v ...

  9. 线上服务器CPU彪高的调试方式

    原文内容来自于LZ(楼主)的印象笔记,如出现排版异常或图片丢失等问题,可查看当前链接:https://app.yinxiang.com/shard/s17/nl/19391737/2fee7b91-f ...

  10. javascript对url进行编码和解码

    这里总结下JavaScript对URL进行编码和解码的三个方法. 为什么要对URL进行编码和解码 只有[0-9[a-Z] $ - _ . + ! * ' ( ) ,]以及某些保留字,才能不经过编码直接 ...