服务端

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服务端和客户端的更多相关文章

  1. 使用PHP创建一个socket服务端

    与常规web开发不同,使用socket开发可以摆脱http的限制.可自定义协议,使用长连接.PHP代码常驻内存等.学习资料来源于workerman官方视频与文档. 通常创建一个socket服务包括这几 ...

  2. [Swift通天遁地]四、网络和线程-(14)创建一个Socket服务端

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  3. 利用IDEA创建Web Service服务端和客户端的详细过程

    创建服务端 一.file–>new–>project 二.点击next后输入服务端名,点击finish,生成目录如下 三.在 HelloWorld.Java 文件中右击,选 WebServ ...

  4. Netty(6)源码-服务端与客户端创建

    原生的NIO类图使用有诸多不便,Netty向用户屏蔽了细节,在与用户交界处做了封装. 一.服务端创建时序图 步骤一:创建ServerBootstrap实例 ServerBootstrap是Netty服 ...

  5. 适合新手:从零开发一个IM服务端(基于Netty,有完整源码)

    本文由“yuanrw”分享,博客:juejin.im/user/5cefab8451882510eb758606,收录时内容有改动和修订. 0.引言 站长提示:本文适合IM新手阅读,但最好有一定的网络 ...

  6. Netty 学习(二):服务端与客户端通信

    Netty 学习(二):服务端与客户端通信 作者: Grey 原文地址: 博客园:Netty 学习(二):服务端与客户端通信 CSDN:Netty 学习(二):服务端与客户端通信 说明 Netty 中 ...

  7. Netty学习笔记(二) 实现服务端和客户端

    在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求. 前置工作 开发环境 J ...

  8. 常量,字段,构造方法 调试 ms 源代码 一个C#二维码图片识别的Demo 近期ASP.NET问题汇总及对应的解决办法 c# chart控件柱状图,改变柱子宽度 使用C#创建Windows服务 C#服务端判断客户端socket是否已断开的方法 线程 线程池 Task .NET 单元测试的利剑——模拟框架Moq

    常量,字段,构造方法   常量 1.什么是常量 ​ 常量是值从不变化的符号,在编译之前值就必须确定.编译后,常量值会保存到程序集元数据中.所以,常量必须是编译器识别的基元类型的常量,如:Boolean ...

  9. Netty服务端与客户端(源码一)

    首先,整理NIO进行服务端开发的步骤: (1)创建ServerSocketChannel,配置它为非阻塞模式. (2)绑定监听,配置TCP参数,backlog的大小. (3)创建一个独立的I/O线程, ...

随机推荐

  1. day08 学习小测试 九九乘法表 车牌划分计算 大文件读取操作

    1.1需求:读取一个100G的文件,检测文件中是否有关键字keys=['苍老师','小泽老师',"alex"], 如果有则替换成"***",并写入到另一个文件中 ...

  2. zombodb 几点说明

    内容来自官方文档,截取部分 默认es 索引的副本为0 这个参考可以通过修改索引,或者在创建的时候通过with 参数指定,或者通过pg 的配置文件中指定 索引更多的列以为这使用了更多的es 能力 索引的 ...

  3. 第一个Python小项目:图片转换成字符图片

    实现的效果:                                                                                               ...

  4. Spring Cloud(Dalston.SR5)--Zuul 网关-微服务集群

    通过 url 映射的方式来实现 zuul 的转发有局限性,比如每增加一个服务就需要配置一条内容,另外后端的服务如果是动态来提供,就不能采用这种方案来配置了.实际上在实现微服务架构时,服务名与服务实例地 ...

  5. 彻底卸载Windows 10中OneDrive

    批处理来源网上. @rem OneDrive Complete uninstaller batch process for Windows 10. @rem Run as administrator ...

  6. 解决scipy无法正确安装到virtualenv中的问题

    一 . pip的基本操作 安装包: pip/pip3 install ***pkg 卸载包: pip/pip3 uninstall ***pkg 查看已经安装的某个包的信息: pip/pip3 sho ...

  7. Delphi 7升级到XE2的字符串问题

    原来的Delphi中有两种字符串:AnsiString和WideString.默认的string即AnsiString.而在Delphi 2009中,新增加了一种UnicodeString.为什么不沿 ...

  8. 前端-JavaScript1-3——JavaScript之字面量

    字面量?????? 字面量:英语叫做literals,有些书上叫做直接量.看见什么,它就是什么. 我们先来学习数字的字面量,和字符串的字面量.剩余的字面量类型,我们日后遇见再介绍. 3.1 数字的字面 ...

  9. mass create DN

    RUN VL10 in the background. http://paperstreetenterprises.com/running-vl10-background/ VL10*开头的TCODE ...

  10. 查看Linux内置命令和外部命令

    1. [hl@localhost ~]$ which cd /bin/cd [hl@localhost ~]$ type cd cd is a shell builtin