在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求。

前置工作

开发环境

  • JDK8
  • Netty版本:5.0.0.Alpha2
  • 集成环境:IDEA
  • 构建工具:Gradle

依赖

    compile group: 'io.netty', name: 'netty-all', version: '5.0.0.Alpha2'compile group: 'org.projectlombok', name: 'lombok', version: '1.18.0'

服务端

Netty服务器主要由两部分组成:

  • 配置服务器功能,如线程、端口
  • 实现服务器处理程序

服务端HandleAdapter

我们是首先实现服务端处理程序,实现Handle要求继承HandleAdapter,这里我们继承SimpleChannelInboundHandler<T>,下面是具体实现的代码信息,其每个函数的作用,我们只需要重写我们所需要的方法即可。


import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;/*** Netty 服务Handle** @author tao*/
@ChannelHandler.Sharable
public class EchoServiceHandle extends SimpleChannelInboundHandler<String> {/*** 接收到新的消息* @param ctx* @param msg* @throws Exception*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {// 打印接收到的消息System.out.println("Netty服务端接收到消息 " + msg);// 回复消息ctx.channel().writeAndFlush("Send ----> 客户端" + ctx.channel().id() + "你好,我已经接收到你发送的消息");}/*** 有新的连接加入* @param ctx* @throws Exception*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("接入新的Channel,id = " + ctx.channel().id());}/*** 服务端发生异常信息的时候* @param ctx* @param cause*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {// 服务端发生异常System.out.println("Netty 服务端发生异常 ,异常信息:" + cause);ctx.close();}@Overrideprotected void messageReceived(ChannelHandlerContext ctx, String msg) {}
}

服务端启动

在服务端的EchoServiceHandle完成之后,我们需要配置服务器的参数信息,比如端口等


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Data;/*** @author tao*/
@Data
public class EchoService {private int port;public void start() throws Exception {EventLoopGroup boosGroup = new NioEventLoopGroup();EventLoopGroup workGroup = new NioEventLoopGroup();try {ServerBootstrap bootstrap = new ServerBootstrap();bootstrap.group(boosGroup, workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//字符串解码器pipeline.addLast(new StringDecoder());//字符串编码器pipeline.addLast(new StringEncoder());//服务端处理器pipeline.addLast(new EchoServiceHandle());}});ChannelFuture sync = bootstrap.bind(port).sync();System.out.println("Netty Service start with " + port + "...");sync.channel().closeFuture().sync();} finally {workGroup.shutdownGracefully();boosGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {EchoService service = new EchoService();service.setPort(8080);service.start();}
}

启动后,我们可以看到启动信息如下:

Netty Service start with 8080...

客户端

客户端和服务端类似,可以相互参考学习.

客户端HandleAdapter

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;@ChannelHandler.Sharable
public class EchoClientHandle extends SimpleChannelInboundHandler<String> {/*** 连接创建成功的时候* @param ctx* @throws Exception*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("channelActive");//连接成功后向服务端发送问候消息ctx.channel().writeAndFlush(Unpooled.copiedBuffer("你好,这里是Netty客户端", CharsetUtil.UTF_8));}/*** 发生异常* @param ctx* @param cause*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {System.out.println("exceptionCaught");cause.printStackTrace();ctx.close();}/*** 接收到服务端发过来的数据* @param ctx* @param msg*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {//打印接收到的数据信息System.out.println("channelRead = " + msg);}@Overrideprotected void messageReceived(ChannelHandlerContext ctx, String msg) {}
}

客户端启动

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;import java.net.InetSocketAddress;/** @author tao */
@Data
@Accessors(chain = true)
@Slf4j
public class EchoClient {private int port;private String host;public void start() throws Exception {EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// 字符串解码器pipeline.addLast(new StringDecoder());// 字符串编码器pipeline.addLast(new StringEncoder());pipeline.addLast(new EchoClientHandle());}});ChannelFuture sync = bootstrap.connect(new InetSocketAddress(host, port)).sync();sync.channel().closeFuture().sync();} catch (Exception e) {e.printStackTrace();} finally {group.shutdownGracefully().sync();}}public static void main(String[] args) throws Exception {EchoClient client = new EchoClient();client.setHost("127.0.0.1").setPort(8080);client.start();}
}

效果

服务端效果

   Netty Service start with 8080...接入新的Channel,id = c0d4f037Netty服务端接收到消息 你好,这里是Netty客户端

客户端效果

channelActive
channelRead = Send ----> 客户端c0d4f037你好,我已经接收到你发送的消息

转载于:https://www.cnblogs.com/zhoutao825638/p/10382157.html

Netty学习笔记(二) 实现服务端和客户端相关推荐

  1. Netty学习笔记二网络编程

    Netty学习笔记二 二. 网络编程 1. 阻塞模式 阻塞主要表现为: 连接时阻塞 读取数据时阻塞 缺点: 阻塞单线程在没有连接时会阻塞等待连接的到达,连接到了以后,要进行读取数据,如果没有数据,还要 ...

  2. ASP.Net学习笔记002--ASP.Net服务端控件做了什么2

    ASP.Net学习笔记002--ASP.Net服务端控件做了什么2 以前写的课程都没有附上源码,很抱歉! 课程中的源码可以加qq索要:1606841559 技术交流qq1群:251572072 技术交 ...

  3. Netty学习笔记(二)Netty服务端流程启动分析

    先贴下在NIO和Netty里启动服务端的代码 public class NioServer { /*** 指定端口号启动服务* */public boolean startServer(int por ...

  4. (SVN笔记)SVN服务端+SVN客户端Tortoise——安装配置

    目录 1.前言 2.官网下载SVN服务端1.14.1 3.安装SVN服务端Server 4.官网下载SVN客户端Tortoise4.3.4 5.安装Tortoise 6.验证Tortoise安装 7. ...

  5. 《精通并发与Netty》学习笔记(02 - 服务端程序编写)

    上节我们介绍了开发netty项目所必需的开发环境及工具的使用,这节我们来写第一个netty项目 开发步骤 第一步:打开https://search.maven.org 找到netty依赖库 第二步:打 ...

  6. PYNQ 采集计划(二)Socket服务端与客户端的搭建,pynq到pc的数据流传输

    文章目录 利用Socket搭建客户端和服务端 简易Socket收发 服务端的搭建 客户端的搭建 真正的视频socket收发 服务端 PC端客户端 进行测试 源码github地址 利用Socket搭建客 ...

  7. Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输

    文章目录 设计思路 代码实现 传输结果 设计思路 运行思路如下 由于在做人脸视频检测的项目的时候需要将检测的人脸区域全部保存下来,并发送到服务器端(用虚拟机来代替),来进行人脸对比,整个代码设计思路如 ...

  8. Netty工作笔记0041---Netty入门--服务端2

    技术交流QQ群[JAVA,C++,Python,.NET,BigData,AI]:170933152 注意这里,pipeline是管道,这主要是用来处理事件的业务的 而通道,主要是用来读数据和写数据的 ...

  9. Web全栈开发学习笔记—Part2 与服务端通信—d.在服务端将数据Alert出来

    目录 REST Sending Data to the Server Changing the importance of notes Extracting communication with th ...

最新文章

  1. 理解GloVe模型(Global vectors for word representation)
  2. RDKit:化合物骨架分析
  3. 计算机网络 物理层链路层
  4. Linux常用监控命令简介 – vmstat,ps,free,uptime 等
  5. 5G 网络接口与基础流程
  6. flutter进行自动编译操作步骤
  7. 《走着瞧》:另类的知青电影
  8. c语言宏定义_C语言宏定义
  9. 关于select的描述计算机,计算机二级考试MySQL数据库每日一练 12月21日
  10. c 并发操作mysql_MySQL并发控制
  11. keepass+onedrive打造密码管理器
  12. bzoj 2257: [Jsoi2009]瓶子和燃料(裴蜀定理)
  13. (附源码)spring boot记账微信小程序 毕业设计 180815
  14. 局域网php服务器搭建,php局域网服务器搭建
  15. docker wordpress 提示:Error establishing a database connection
  16. newLISP你也行 --- 字符串
  17. tf-toturial
  18. 〖Python 数据库开发实战 - MySQL篇⑥〗- 利用 PyCharm 链接 MySQL 实现数据库可视化
  19. 智慧社区解决方案核心要点有哪些 智慧社区解决方案
  20. 浅析dToF和iToF成像技术

热门文章

  1. 纵向表格_Excel如何把横向数据变纵向?教你一键快速实现
  2. Oracle的ONS创建,Oracle 10gR2 RAC Clusterware ONS服务的管理
  3. 融合机器人技术和神经科学的神经工程未来与挑战
  4. [UE4蓝图教程]蓝图入门之蓝图通信机制入门
  5. AI破解古文字登Nature封面:修复缺失文字,精确地理位置和书写时间,DeepMind哈佛谷歌多家联手开发...
  6. SCI期刊上发现大量辣眼学术名词,用机翻规避抄袭,作者主要来自中国
  7. 李飞飞、颜宁等8位华人学者入选美国艺术与科学院院士,其中7位女性
  8. 量产加速!干线物流创新中心迎地平线入伙,嬴彻地平线达成战略合作
  9. Python之流程控制
  10. 微信小程序之可滚动视图容器组件 scroll-view