通过简单代码实现服务端与服务端

本文章只做简单学习交流,如工作需要,请合理配置搭建。

详细讲解在代码注释中。上货!!!!

1、引入包

pom.xml中引入

<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.20.Final</version></dependency>

2、服务端搭建

import com.wing.rpc.netty.HelloChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;import java.net.InetSocketAddress;/*** TCP  服务端** @Author wing* @Date 2021/8/18 9:15**/
public class NettyServer {public static void main(String[] args) {System.out.println("----------------------Netty Socket Start.----------------------------");System.out.println("----------------------Netty Socket Start..----------------------------");System.out.println("----------------------Netty Socket Start...----------------------------");System.out.println("----------------------Netty Socket Start....----------------------------");System.out.println("----------------------Netty Socket Start.....----------------------------");System.out.println("----------------------Netty Socket start......----------------------------");//创建一个EventLoopGroup,是创建netty TCP服务器的第一步。// 此为示例代码,group只写一个EventLoopGroup group = new NioEventLoopGroup();try {// 创建Bootstrap,netty中 Bootstrap负责引导:启动线程、打开Socket等// 注意:TCP服务器使用ServerBootStrap,TCP客户端使用BootStrap实例。ServerBootstrap serverBootstrap = new ServerBootstrap();// 配置组serverBootstrap.group(group);// 配置Channel,Netty SocketChannel表示通过网络与另一台计算机的TCP连接,无论客户端还是服务端都需要SocketChannel来进行实例传递。// SocketChannel由EventLoop管理,并且始终仅由同一个EventLoop管理。由于EventLoop始终由同一个线程执行,因此SocketChannel实例也仅有同一线程访问。// 因此从SocketChannel读取不必担心同步问题。serverBootstrap.channel(NioServerSocketChannel.class);//设置服务端地址端口serverBootstrap.localAddress(new InetSocketAddress("localhost", 9090));// ChannelHandel处理Netty SocketChannel接收的数据。ChannelHandler还可以处理写入Channel的数据。serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {// 初始化通道@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {            // 管道socketChannel.pipeline().addLast(new ServerHandler());}});// 启动服务// ChannelFuture是了解服务器的绑定(ip、端口)何时完成ChannelFuture channelFuture = serverBootstrap.bind().sync();System.out.println("----------------------Netty Socket Start Success----------------------------");channelFuture.channel().closeFuture().sync();System.out.println("----------------------Netty Socket Stop Success----------------------------");} catch (InterruptedException e) {e.printStackTrace();} finally {try {group.shutdownGracefully().sync();} catch (InterruptedException e) {e.printStackTrace();}}}
}

自定义处理器: ServerHandler

package com.wing.rpc.netty;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;/*** @Author wing* @Date 2021/8/18 9:41**/
public class ServerHandler extends ChannelInboundHandlerAdapter {/**** 读取数据及响应* @param ctx* @param msg* @throws Exception*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf inBuffer = (ByteBuf) msg;String receive = inBuffer.toString(CharsetUtil.UTF_8);System.out.println("服务端接收到的数据: " + receive);ctx.write(Unpooled.copiedBuffer("Hello : " + receive, CharsetUtil.UTF_8));}/**** 读取完成* :::: channel中没有可读取的数据时调用* @param ctx* @throws Exception*/@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);}/**** 程序异常处理* ::::: 从接受或发送数据时抛出异常,则调用该方法,在这里可以设置关闭,错误码等操作。* @param ctx* @param cause* @throws Exception*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}

至此 基于TCP连接的Netty 客户端搭建完毕

3、客户端

客户端与服务端代码相似,却有不同,不要混淆。
比如: 配置通道时:客户端-NioSocketChannel,服务端-NioServerSocketChannel


import com.wing.rpc.netty.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;/*** TCP  客户端** @Author wing* @Date 2021/8/18 10:13**/
public class NettyClient {public static void main(String[] args) {System.out.println("----------------------Netty Client Start.----------------------------");System.out.println("----------------------Netty Client Start..----------------------------");System.out.println("----------------------Netty Client Start...----------------------------");System.out.println("----------------------Netty Client Start....----------------------------");System.out.println("----------------------Netty Client Start.....----------------------------");System.out.println("----------------------Netty Client Start......----------------------------");// 创建 EventLoopGroup 实例代码 只写一个EventLoopGroup group = new NioEventLoopGroup();try {// 创建BootStrap,注意:TCP服务器使用ServerBootStrap,TCP客户端使用BootStrap实例。Bootstrap bootstrap = new Bootstrap();// 配置组bootstrap.group(group);// 配置Channelbootstrap.channel(NioSocketChannel.class);// 配置连接(请求) 地址bootstrap.remoteAddress(new InetSocketAddress("localhost", 9090));// 配置处理器// 1、 创建一个ChannelInitializer并将其附加到BootStrapbootstrap.handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {// 管道socketChannel.pipeline().addLast(new ClientHandler());}});//启动客户端ChannelFuture channelFuture = bootstrap.connect().sync();System.out.println("----------------------Netty Client Start Success----------------------------");// 等待客户端关闭channelFuture.channel().closeFuture().sync();System.out.println("----------------------Netty Client Stop Success----------------------------");} catch (InterruptedException e) {e.printStackTrace();} finally {try {group.shutdownGracefully().sync();} catch (InterruptedException e) {e.printStackTrace();}}}
}

自定义处理器:ClientHandler


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;/*** @Author wing* @Date 2021/8/18 10:17**/
public class ClientHandler extends SimpleChannelInboundHandler {@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//刷新读写(发送给服务端的数据)ctx.writeAndFlush(Unpooled.copiedBuffer("Netty Rocks!", CharsetUtil.UTF_8));}/**** 读取通道数据* @param channelHandlerContext* @param o* @throws Exception*/@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {ByteBuf byteBuf = (ByteBuf) o;System.out.println("客户端接受到的服务端返回的数据: " + byteBuf.toString(CharsetUtil.UTF_8));}/**** 异常处理* @param ctx* @param cause* @throws Exception*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}

客户端搭建完毕

4、测试

服务端:

----------------------Netty Socket Start.----------------------------
----------------------Netty Socket Start..----------------------------
----------------------Netty Socket Start...----------------------------
----------------------Netty Socket Start....----------------------------
----------------------Netty Socket Start.....----------------------------
----------------------Netty Socket start......----------------------------
----------------------Netty Socket Start Success----------------------------
服务端接收到的数据: Netty Rocks!

客户端:

----------------------Netty Client Start.----------------------------
----------------------Netty Client Start..----------------------------
----------------------Netty Client Start...----------------------------
----------------------Netty Client Start....----------------------------
----------------------Netty Client Start.....----------------------------
----------------------Netty Client Start......----------------------------
----------------------Netty Client Start Success----------------------------
客户端接受到的服务端返回的数据: Hello : Netty Rocks!
----------------------Netty Client Stop Success----------------------------

完毕!!!

本文章只做简单学习使用,工作中使用请合理搭建配置。

友情提示: 了解Java NIO 对 Netty的学习很有帮助,建议大家熟练掌握

后续有时间会继续更新,深入。

Netty的服务端和客户端相关推荐

  1. netty tcp服务端主动断开客户端_【Netty】服务端和客户端

    欢迎关注公众号:[爱编程] 如果有需要后台回复2019赠送1T的学习资料哦!! 本文是基于Netty4.1.36进行分析 服务端 Netty服务端的启动代码基本都是如下: private void s ...

  2. Netty入门系列(1) --使用Netty搭建服务端和客户端

    引言 前面我们介绍了网络一些基本的概念,虽然说这些很难吧,但是至少要做到理解吧.有了之前的基础,我们来正式揭开Netty这神秘的面纱就会简单很多. 服务端 public class PrintServ ...

  3. 使用 Netty 实现服务端和客户端的点对多点通信——聊天室功能

    一 需求 1 监听所有客户端的上线和下线. 2 将某一个客户端的上线和离线情况,转告给其他客户端"客户端XX上/下线" 3 客户端先将消息发送给服务端,服务端再将此消息转发给所有客 ...

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

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

  5. Netty实现服务端客户端长连接通讯及心跳检测

    通过netty实现服务端与客户端的长连接通讯,及心跳检测. 基本思路:netty服务端通过一个Map保存所有连接上来的客户端SocketChannel,客户端的Id作为Map的key.每次服务器端如果 ...

  6. DotNetty 高性能NIO通讯模型 服务端和客户端案例版

    Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的高性能客户端/服务器 通讯框架. Netty的优势: 并发高 传输快 封装好 还有一个叫做 内存零 ...

  7. Netty的Socket编程详解-搭建服务端与客户端并进行数据传输

    场景 Netty在IDEA中搭建HelloWorld服务端并对Netty执行流程与重要组件进行介绍: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article ...

  8. netty服务器返回信息关闭,netty4 服务端同步客户端返回的结果

    netty是一个异步通讯框架,在有的时候咱们想使用服务端向客户端发送消息,服务端同步等待客户端返回结果真进行下一步的业务逻辑操做.那要怎么作才能同步获取客户端返回的数据呢?这里我用到了JDK中的闭锁等 ...

  9. Netty实战 IM即时通讯系统(八)服务端和客户端通信协议编解码

    Netty实战 IM即时通讯系统(八)服务端和客户端通信协议编解码 零. 目录 IM系统简介 Netty 简介 Netty 环境配置 服务端启动流程 客户端启动流程 实战: 客户端和服务端双向通信 数 ...

最新文章

  1. java map key是否存在_java中如何判断map集合中是否存在key
  2. docker 容器restarting_FATE联邦学习docker-compose部署中的坑
  3. 边缘使用 K8s 门槛太高?OpenYurt 这个功能帮你快速搭建集群!
  4. 微信小程序的页面渲染(if/for)
  5. 解决一个驱动代码解耦合问题
  6. Windows平台真实时毫秒级4K H264/H265直播技术方案探讨
  7. Linux虚拟机重启后无法获取IP的问题(断网、没网)
  8. 守护进程: supervisor使用
  9. 《玩转D语言系列》三、轻松大跃进,把它当C语言先用起来
  10. CC***原理及防范方法
  11. 摇一摇周边:微信是这样连接线下商户的
  12. Python小测验(01)
  13. Serializers
  14. go get golang.org/x/tools 失败解决
  15. cocosLua 之cocosStudio动画
  16. 近3千多道小学语数英知识题ACCESS数据库
  17. 【安卓小程序】app 首页
  18. 2023年JAVA面试宝典(全网最全未来十年可用)
  19. katana(武士刀)setuid提权
  20. python正则表达式匹配专利号

热门文章

  1. 超右脑学习~那个小日本滴~
  2. 分享一款很好的视频处理软件 会声会影X8(huishenghuiyingx8-trial_x64)
  3. java程序编六角星_CSS实现五角星、六角星
  4. mysql 找回误删表的数据办法_mysql找回误删表的数据方法(必看)
  5. 对计算机科学的反思(转计算所李国杰文章)
  6. 决战Go语言从入门到入土v0.1
  7. 【已解决】VS2019下载超慢的问题
  8. 【面试】京东成都研发部面试
  9. 映泰主板BIOS刷入slic并激活
  10. echarts柱状图改进度图常用配置