服务端

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. es6模块与 commonJS规范的区别

    https://www.cnblogs.com/weblinda/p/6740833.html

  2. Ubuntu16.04中pip无法更新升级,采用源码方式安装

    1.从pip官网下载最新版 https://pypi.org/project/pip/#files 2.ubuntu中创建文件位置,我的放在一下路径,之后进行解压 3.解压后进入pip的文件夹,在执行 ...

  3. js barcode 打印

    新建 html <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset=&quo ...

  4. ESP8266EX资料

    https://github.com/esp8266/Arduino http://espressif.com/zh-hans/support/explore/faq 电路资料图如下: 介绍功能: 参 ...

  5. 421. Maximum XOR of Two Numbers in an Array

    这题要求On时间复杂度完成, 第一次做事没什么思路的, 答案网上有不贴了, 总结下这类题的思路. 不局限于这个题, 凡是对于这种给一个  数组,  求出 xxx 最大值的办法, 可能上来默认就是dp, ...

  6. Spring Boot 非常好的学习资料

    from@https://gitee.com/didispace/SpringBoot-Learning Spring Boot 2.0 新特性学习 简介与概览 Spring Boot 2.0 正式发 ...

  7. 内置---排序(sorted)

    # li = [1,23,4,5,6,6,7]# res = sorted(li,reverse=True) #反转后,从小到大 默认从大到小 #res = sorted(li) # print(re ...

  8. prettier-eslint 与 prettier-eslint-cli 区别

    prettier-eslint 与 prettier-eslint-cli 区别: prettier-eslint 只能处理字符串 prettier-eslint-cli 能处理一个或多个文件 默认情 ...

  9. UDP广播包

    一,广播地址: 广播地址是专门用于同时向网络中所有工作站进行发送的一个地址.在使用TCP/IP 协议的网络中,主机号为全1的IP地址为广播地址.例如,对于 :192.168.199.0(掩码:255. ...

  10. Caused by: io.protostuff.ProtobufException: Protocol message contained an invalid tag (zero).

    [ERROR] com.xxxx.redis.RedisClientTemplate.getOject(RedisClientTemplate.java:60):http-bio-8080-exec- ...