netty(二) 创建一个netty服务端和客户端
服务端
NettyServer
package com.zw.netty.config; import com.zw.netty.channel.ServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; /**
* @author liuzw
* @email liuzw1@hua-cloud.com.cn
* @date 2018/12/20 20:39
*/
public class NettyServer { private final int port; public NettyServer(Integer port){
this.port = port;
} public void startServer(){
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.option(ChannelOption.TCP_NODELAY, true);
b.childHandler(new ServerInitializer());
b.handler(new LoggingHandler(LogLevel.INFO));
b.childOption(ChannelOption.AUTO_READ, true); // 服务器绑定端口监听
ChannelFuture f = b.bind(port).sync(); // 监听服务器关闭监听
f.channel().closeFuture().sync(); }catch (InterruptedException e){ }finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} public static void main(String [] args){
new NettyServer(8081).startServer();
}
}
ChannelInitializer
package com.zw.netty.channel; import com.zw.netty.handler.GpsHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil; /**
* @author liuzw
* @email liuzw1@hua-cloud.com.cn
* @date 2018/12/20 20:55
*/
public class ServerInitializer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 以("\n")为结尾分割的 解码器
// pipeline.addLast("lenth",new FixedLengthFrameDecoder(7));
// pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
// pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Unpooled.wrappedBuffer(new byte[] { '#' })));
// pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
// pipeline.addLast(new LengthFieldPrepender(4)); // 字符串解码 和 编码
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder()); // 自己的逻辑Handler
pipeline.addLast("handler", new GpsHandler());
}
}
ChannelHandler
package com.zw.netty.handler; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import java.net.InetAddress;
import java.nio.charset.Charset;
import java.time.LocalDateTime; /**
* @author liuzw
* @email liuzw1@hua-cloud.com.cn
* @date 2018/12/20 21:03
*/
public class GpsHandler extends SimpleChannelInboundHandler<String> { @Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println("RamoteAddress : " + channelHandlerContext.channel().remoteAddress() + " active !");
System.out.println(s);
// channelHandlerContext.channel().writeAndFlush("from server;" + LocalDateTime.now()); } /**
* 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
*
* */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !"); } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// 当出现异常就关闭连接
ctx.close();
}
}
客户端
ClientServer
package com.zw.netty; 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.NioSocketChannel; /**
* @author liuzw
* @email liuzw1@hua-cloud.com.cn
* @date 2018/12/21 9:49
*/
public class ClientServer { public static void main(String[] args) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new MyClientInitializer()); try {
ChannelFuture channelFuture = bootstrap.connect("localhost", 9005).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
eventLoopGroup.shutdownGracefully();
}
}
}
ChannelInitializer
package com.zw.netty; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
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; /**
* @author liuzw
* @email liuzw1@hua-cloud.com.cn
* @date 2018/12/21 9:50
*/
public class MyClientInitializer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// pipeline.addLast(new FixedLengthFrameDecoder(7));
// pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
// pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyClientHandler());
} }
ChannelHandler
package com.zw.netty; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; import java.time.LocalDateTime; /**
* @author liuzw
* @email liuzw1@hua-cloud.com.cn
* @date 2018/12/21 9:52
*/
public class MyClientHandler extends SimpleChannelInboundHandler<String> { @Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress());
System.out.println("client output:" + msg);
ctx.writeAndFlush("from client;" + LocalDateTime.now()); } @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
cause.printStackTrace();
ctx.channel().close();
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("----------------------");
// ctx.writeAndFlush("test#");
ctx.writeAndFlush("test1 ");
// ctx.writeAndFlush("test11111111111");
} }
netty(二) 创建一个netty服务端和客户端的更多相关文章
- 使用PHP创建一个socket服务端
与常规web开发不同,使用socket开发可以摆脱http的限制.可自定义协议,使用长连接.PHP代码常驻内存等.学习资料来源于workerman官方视频与文档. 通常创建一个socket服务包括这几 ...
- [Swift通天遁地]四、网络和线程-(14)创建一个Socket服务端
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- 利用IDEA创建Web Service服务端和客户端的详细过程
创建服务端 一.file–>new–>project 二.点击next后输入服务端名,点击finish,生成目录如下 三.在 HelloWorld.Java 文件中右击,选 WebServ ...
- Netty(6)源码-服务端与客户端创建
原生的NIO类图使用有诸多不便,Netty向用户屏蔽了细节,在与用户交界处做了封装. 一.服务端创建时序图 步骤一:创建ServerBootstrap实例 ServerBootstrap是Netty服 ...
- 适合新手:从零开发一个IM服务端(基于Netty,有完整源码)
本文由“yuanrw”分享,博客:juejin.im/user/5cefab8451882510eb758606,收录时内容有改动和修订. 0.引言 站长提示:本文适合IM新手阅读,但最好有一定的网络 ...
- Netty 学习(二):服务端与客户端通信
Netty 学习(二):服务端与客户端通信 作者: Grey 原文地址: 博客园:Netty 学习(二):服务端与客户端通信 CSDN:Netty 学习(二):服务端与客户端通信 说明 Netty 中 ...
- Netty学习笔记(二) 实现服务端和客户端
在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求. 前置工作 开发环境 J ...
- 常量,字段,构造方法 调试 ms 源代码 一个C#二维码图片识别的Demo 近期ASP.NET问题汇总及对应的解决办法 c# chart控件柱状图,改变柱子宽度 使用C#创建Windows服务 C#服务端判断客户端socket是否已断开的方法 线程 线程池 Task .NET 单元测试的利剑——模拟框架Moq
常量,字段,构造方法 常量 1.什么是常量 常量是值从不变化的符号,在编译之前值就必须确定.编译后,常量值会保存到程序集元数据中.所以,常量必须是编译器识别的基元类型的常量,如:Boolean ...
- Netty服务端与客户端(源码一)
首先,整理NIO进行服务端开发的步骤: (1)创建ServerSocketChannel,配置它为非阻塞模式. (2)绑定监听,配置TCP参数,backlog的大小. (3)创建一个独立的I/O线程, ...
随机推荐
- Ajax请求传递数组参数
var ids = []; var rows=$("#tt").datagrid("getSelections"); for(var i=0; i<row ...
- C++ 值传递、指针传递、引用传递详解
C++ 值传递.指针传递.引用传递详解 最近写了几篇深层次讨论数组和指针的文章,其中提到了“C语言中,所有非数组的形式参数传递均以值传递形式” 数组和指针背后——内存角度 语义"陷阱&quo ...
- Python的深copy和浅copy
浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象. 深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象. 浅copy: a = [1, 2, ...
- javascript运行机制之执行顺序详解
1.代码块 指的的是有标签分割的代码段. 例如: <script type="text/javascript"> alert("这是代码块一"); ...
- ROS下利用realsense采集RGBD图像合成点云
摘要:在ROS kinetic下,利用realsense D435深度相机采集校准的RGBD图片,合成点云,在rviz中查看点云,最后保存成pcd文件. 一. 各种bug 代码编译成功后,打开rviz ...
- mosquitto centos安装配置
周末弄wordpress的Mysql,一不小心把wordpress弄不好了,写了的好几遍文章也没有了,一怒之下,把整个系统重装了,安装了不带任何软件的新系统,重新搭一遍. 0.安装ftp服务器 #yu ...
- 如何判断ACCESS数据库有无密码
因为没有密码的数据库即使加上密码选项连接也不报错,所以如果通过连接来判读就无法识别无密码的数据库. 通过设置密码可以来测试数据库是否有密码,这是由于修改数据库密码的前提是数据库必须先有密码才行,如果数 ...
- ssl协议相关
<1> SSL版本 测试浏览器支持的SSL版本的网站: https://www.ssllabs.com/ssltest/viewMyClient.html 0xfefd (DTLS ...
- HTML---仿网易新闻登录页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- MAC地址表、ARP缓存表以及路由表
一:MAC地址表详解 说到MAC地址表,就不得不说一下交换机的工作原理了,因为交换机是根据MAC地址表转发数据帧的.在交换机中有一张记录着局域网主机MAC地址与交换机接口的对应关系的表,交换机就是根据 ...