总体来说只需要三个步骤,下面详细介绍

第一步 创建SpringBoot工程snetty

第二步 创建子模块也就是ModuleClient,Server,均为SpringBoot工程

第三步 将服务器端和客户端的代码分别打成Jar包,运行Jar包。因为Netty需要客户端与服务器端两个端口才能看到效果,但是IDE的console只有一个窗口,所以需要将两个端口代码分别打成Jar包,这样再运行的话,就有两个窗口了。

先说一下遇到的问题,具体代码在下边。

打包运行

因为我运行Jar包使用的是mvn exec:java这个命令,是将主函数main的参数构建在pom.xml文件中。

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>run-server</id>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.bihang.server.server2.EchoServer</mainClass>
<arguments>
<argument>${echo-server.port}</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>

也就是说当我用mvn clean package这个命令将服务器端的代码打成Jar包之后,再运行mvn exec:java命令,此时服务器端就启动了。

<mainClass>com.bihang.server.server2.EchoServer</mainClass>这里放的就是主函数。

<arguments>
<argument>${echo-server.port}</argument>
</arguments>

这里放的是主函数的参数。

获取父级pom.xml的信息

${echo-server.port}这个值是从父级pom.xml中的properties中获取的,很关键的就是,在子模块Server的pom.xml中的<parent>标签中要这么写才能获得父级pom.xml中的信息。

<parent>
<groupId>com.bihang</groupId>
<artifactId>snetty</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
</parent>

父级中的properties:

<properties>
<java.version>1.8</java.version>
<echo-server.hostname>127.0.0.1</echo-server.hostname>
<echo-server.port>8888</echo-server.port>
</properties>

并且父级中的<packaging>标签要改成pom形式

<packaging>pom</packaging>

具体代码

引入依赖

<!--Netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.36.Final</version>
</dependency>
<!--Netty END-->
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

服务器端和客户端都只需要两部分代码,一个是处理器程序,一个是引导程序。

服务器端的EchoServerHandler

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil; @ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
System.out.println(
"Server received: " + in.toString(CharsetUtil.UTF_8));
ctx.write(in);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

服务器端的EchoServer

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; public class EchoServer {
private final int port; public EchoServer(int port) {
this.port = port;
} public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println(
"Usage: " + EchoServer.class.getSimpleName() +
" <port>");
}
int port = Integer.parseInt(args[0]);
new EchoServer(port).start();
} public void start() throws Exception {
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
}

客户端的EchoClientHandler

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; public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { //在到服务器的连接已经建立之后将被调用
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",
CharsetUtil.UTF_8));
}
//当从服务器接收到一条消息时被调用
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
System.out.println(
"Client received: " + in.toString(CharsetUtil.UTF_8));
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

客户端的EchoClient

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; public class EchoClient {
private final String host;
private final int port; public EchoClient(String host, int port) {
this.host = host;
this.port = port;
} public void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(
new EchoClientHandler());
}
});
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
} public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println(
"Usage: " + EchoClient.class.getSimpleName() +
" <host> <port>");
return;
}
String host = args[0];
int port = Integer.parseInt(args[1]);
new EchoClient(host, port).start();
}
}

SpringBoot整合Netty的更多相关文章

  1. SpringBoot整合Netty并使用Protobuf进行数据传输(附工程)

    前言 本篇文章主要介绍的是SpringBoot整合Netty以及使用Protobuf进行数据传输的相关内容.Protobuf会简单的介绍下用法,至于Netty在之前的文章中已经简单的介绍过了,这里就不 ...

  2. springboot整合netty(二)

    目录 前言 正文 代码 1. 新建一个springboot项目,在pom文件中添加netty依赖: 2.新建netty服务 3.netty调用所需的服务类 4 springboot启动类 5.测试 我 ...

  3. springboot整合netty的多种方式

    netty作为一个高性能的io框架,是非好用的一个技术框架, Netty 是一个基于NIO的客户.服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户. ...

  4. springboot整合netty,多种启动netty的方式,展现bean得多种启动方法

    首先讲解下,spring中初始化加载问题: 很多时候,我们自己写的线程池,还有bean对象,还有其他的服务类,都可以通过,相关注解进行交给spring去管理,那么我们如何让nettyserver初始化 ...

  5. 第6章 使用springboot整合netty搭建后台

    我们不会去使用自增长的id,在现阶段的互联网开发过程中,自增长的id是已经不适用了.在未来随着系统版本的迭代,用户数量的递增,肯定会做分库分表,去做一些相应的切分.在这个时候我们就需要有一个唯一的id ...

  6. SpringBoot整合Netty实现socket通讯简单demo

    依赖 <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifa ...

  7. SpringBoot整合Redis使用Restful风格实现CRUD功能

    前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...

  8. SpringBoot整合Swagger和Actuator

    前言 本篇文章主要介绍的是SpringBoot整合Swagger(API文档生成框架)和SpringBoot整合Actuator(项目监控)使用教程. SpringBoot整合Swagger 说明:如 ...

  9. SpringBoot整合Guacamole教程

    前言 本文主要介绍的是SpringBoot如何整合Guacamole在浏览器是远程桌面的访问. Guacamole 介绍 Apache Guacamole 是一个无客户端远程桌面网关.它支持标准协议, ...

随机推荐

  1. 关于 IPv6

    http://test-ipv6.com/ http://bbs.chinaunix.net/thread-1799798-1-1.html

  2. spring cloud学习(六) 配置中心-自动更新

    上一篇学习了spring cloud config的基本使用,但发现有个问题,就是每次更改配置后,都需要重启服务才能更新配置,这样肯定是不行的.在上网查资料了解后,spring cloud支持通过AM ...

  3. 修改tomcat默认端口号

    修改tomcat端口号 端口修改tomcat tomcat服务器的默认端口号是8080 1 只启动一个tomcat的情况 当我们不想使用8080端口,需要修改为其他端口时,我们可以: 1, 打开tom ...

  4. Python小白学习之路(二十三)—【生成器补充】

    生成器的一些补充 接着下鸡蛋和吃包子! 补充一:生成器只能遍历一次 (总是把生成器比喻成母鸡下鸡蛋,需要一个下一个,首先是下出来的鸡蛋不能塞回母鸡肚子里,其次是一个母鸡一生只能下一定数量的鸡蛋,下完了 ...

  5. 在Ubuntu下编译安装nginx

    一.安装nginx 1.安装前提 a)epoll,linux内核版本为2.6或者以上 b)gcc编译器,g++编译器 c)pcre库,函数库,支持解析正则表达式 d)zlib库:压缩解压功能 e)op ...

  6. git中多账号切换问题的解决方案(转)

    作者:知乎用户链接:https://www.zhihu.com/question/23028445/answer/416231632来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请 ...

  7. Scala使用Akka模拟RPC机制代码2

    RemoteMessage.scala //对象要序列化才能通过网络传输 这个地方没有大括号....这有这个extends声明 trait RemoteMessage extends Serializ ...

  8. Android开发中实现https校验

    在安卓开发中需要自己写代码实现校验公钥的功能 当然,  如果是自己服务器,就不用校验, 如果是别人的服务器,比如银行,就需要校验 在这里, 小编采用从github上下载的开源框架实现,在开源框架中添加 ...

  9. 理解 async/await 的执行

    这是一篇简单的短文章,方便理解. 开局先丢官宣:sec-async-function-definitions 这个链接是对 await 的解释,解释了它的执行. await 的执行意味着(官宣巴拉巴拉 ...

  10. java EE第一周博客

    一,课程目标 能够完成javaee开发框架的深入学习,能够熟练的构建出基本开发框架,熟练掌握配置文件以及各种插件的应用.实现一个较为复杂的javaee项目 二.企业级应用与互联网应用的区别 企业级应用 ...