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线程, ...
随机推荐
- (26)基于cookie的登陆认证(写入cookie、删除cookie、登陆后所有域下的网页都可访问、登陆成功跳转至用户开始访问的页面、使用装饰器完成所有页面的登陆认证)
获取cookie request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age ...
- Java_IO_文件的续写_小笔记
package IO; import java.io.FileWriter; import java.io.IOException; class FileWrite_WenJianXuXie { /* ...
- Excel转datatable
如果想支持 .xls,.xlsx 两种格式 则必须安装一个exe文件,下载路径https://www.microsoft.com/zh-CN/download/details.aspx?id=1325 ...
- Python hashlib&hmac 模块
用于加密相关的操作,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法 hashlib模块示例: import hashlib m = hashlib. ...
- IndentationError:expected an indented block错误解决
Python语言是一款对缩进非常敏感的语言,给很多初学者带来了困惑,即便是很有经验的Python程序员,也可能陷入陷阱当中.最常见的情况是tab和空格的混用会导致错误,或者缩进不对,而这是用肉眼无法分 ...
- spring @Autowired注入对象,在构造方法中为null问题
出现问题的代码如下: @Service public class BaseHttpServiceImpl implements BaseHttpClient { private final stati ...
- CSS之边框
<!DOCTYPE html> <!--边框--> <html lang="en"> <head> <meta charset ...
- javascript常用工具类整理(copy)
JavaScript常用工具类 类型 日期 数组 字符串 数字 网络请求 节点 存储 其他 1.类型 isString (o) { //是否字符串 return Object.prototype.to ...
- 基于form表单 写登陆注册
urls urlpatterns = [ url(r'^admin/', admin.site.urls), # 登录界面url(r'^login/$', views.login,name='logi ...
- bitbucket 上公钥SSH key如何add key并进行项目运用
前提:从sourcetree 添加项目时老是拉取不下来,查到原因是应为bitbucket需要SSH key公钥 目的:公钥相当于你在任何一台电脑只要有公钥授权就可以随时提交代码到服务器 原因: 1.很 ...