- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Java NIO框架Netty简单使用的示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
之前写了一篇文章:Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码),介绍了如何使用Java原生IO支持进行网络编程,本文介绍一种更为简单的方式,即Java NIO框架.
Netty是业界最流行的NIO框架之一,具有良好的健壮性、功能、性能、可定制性和可扩展性。同时,它提供的十分简单的API,大大简化了我们的网络编程.
同Java IO介绍的文章一样,本文所展示的例子,实现了一个相同的功能.
1、服务端 。
Server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package
com.anxpp.io.calculator.netty;
import
io.netty.bootstrap.ServerBootstrap;
import
io.netty.channel.ChannelFuture;
import
io.netty.channel.ChannelInitializer;
import
io.netty.channel.ChannelOption;
import
io.netty.channel.EventLoopGroup;
import
io.netty.channel.nio.NioEventLoopGroup;
import
io.netty.channel.socket.SocketChannel;
import
io.netty.channel.socket.nio.NioServerSocketChannel;
public
class
Server {
private
int
port;
public
Server(
int
port) {
this
.port = port;
}
public
void
run()
throws
Exception {
EventLoopGroup bossGroup =
new
NioEventLoopGroup();
EventLoopGroup workerGroup =
new
NioEventLoopGroup();
try
{
ServerBootstrap b =
new
ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.
class
)
.option(ChannelOption.SO_BACKLOG,
1024
)
.childOption(ChannelOption.SO_KEEPALIVE,
true
)
.childHandler(
new
ChannelInitializer<SocketChannel>() {
@Override
public
void
initChannel(SocketChannel ch)
throws
Exception {
ch.pipeline().addLast(
new
ServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
System.out.println(
"服务器开启:"
+port);
f.channel().closeFuture().sync();
}
finally
{
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public
static
void
main(String[] args)
throws
Exception {
int
port;
if
(args.length >
0
) {
port = Integer.parseInt(args[
0
]);
}
else
{
port =
9090
;
}
new
Server(port).run();
}
}
|
ServerHandler:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package
com.anxpp.io.calculator.netty;
import
io.netty.buffer.ByteBuf;
import
io.netty.buffer.Unpooled;
import
io.netty.channel.ChannelHandlerContext;
import
io.netty.channel.ChannelInboundHandlerAdapter;
import
java.io.UnsupportedEncodingException;
import
com.anxpp.io.utils.Calculator;
public
class
ServerHandler
extends
ChannelInboundHandlerAdapter {
@Override
public
void
channelRead(ChannelHandlerContext ctx, Object msg)
throws
UnsupportedEncodingException {
ByteBuf in = (ByteBuf) msg;
byte
[] req =
new
byte
[in.readableBytes()];
in.readBytes(req);
String body =
new
String(req,
"utf-8"
);
System.out.println(
"收到客户端消息:"
+body);
String calrResult =
null
;
try
{
calrResult = Calculator.Instance.cal(body).toString();
}
catch
(Exception e){
calrResult =
"错误的表达式:"
+ e.getMessage();
}
ctx.write(Unpooled.copiedBuffer(calrResult.getBytes()));
}
@Override
public
void
channelReadComplete(ChannelHandlerContext ctx)
throws
Exception {
ctx.flush();
}
/**
* 异常处理
*/
@Override
public
void
exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
package
com.anxpp.io.calculator.netty;
import
io.netty.buffer.ByteBuf;
import
io.netty.buffer.Unpooled;
import
io.netty.channel.ChannelHandlerContext;
import
io.netty.channel.ChannelInboundHandlerAdapter;
import
java.io.UnsupportedEncodingException;
import
com.anxpp.io.utils.Calculator;
public
class
ServerHandler
extends
ChannelInboundHandlerAdapter {
@Override
public
void
channelRead(ChannelHandlerContext ctx, Object msg)
throws
UnsupportedEncodingException {
ByteBuf in = (ByteBuf) msg;
byte
[] req =
new
byte
[in.readableBytes()];
in.readBytes(req);
String body =
new
String(req,
"utf-8"
);
System.out.println(
"收到客户端消息:"
+body);
String calrResult =
null
;
try
{
calrResult = Calculator.Instance.cal(body).toString();
}
catch
(Exception e){
calrResult =
"错误的表达式:"
+ e.getMessage();
}
ctx.write(Unpooled.copiedBuffer(calrResult.getBytes()));
}
@Override
public
void
channelReadComplete(ChannelHandlerContext ctx)
throws
Exception {
ctx.flush();
}
/**
* 异常处理
*/
@Override
public
void
exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
|
2、客户端 。
Client:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package
com.anxpp.io.calculator.netty;
import
io.netty.bootstrap.Bootstrap;
import
io.netty.channel.ChannelFuture;
import
io.netty.channel.ChannelInitializer;
import
io.netty.channel.ChannelOption;
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.util.Scanner;
public
class
Client
implements
Runnable{
static
ClientHandler client =
new
ClientHandler();
public
static
void
main(String[] args)
throws
Exception {
new
Thread(
new
Client()).start();
@SuppressWarnings
(
"resource"
)
Scanner scanner =
new
Scanner(System.in);
while
(client.sendMsg(scanner.nextLine()));
}
@Override
public
void
run() {
String host =
"127.0.0.1"
;
int
port =
9090
;
EventLoopGroup workerGroup =
new
NioEventLoopGroup();
try
{
Bootstrap b =
new
Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.
class
);
b.option(ChannelOption.SO_KEEPALIVE,
true
);
b.handler(
new
ChannelInitializer<SocketChannel>() {
@Override
public
void
initChannel(SocketChannel ch)
throws
Exception {
ch.pipeline().addLast(client);
}
});
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
finally
{
workerGroup.shutdownGracefully();
}
}
}
|
ClientHandler:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package
com.anxpp.io.calculator.netty;
import
io.netty.buffer.ByteBuf;
import
io.netty.buffer.Unpooled;
import
io.netty.channel.ChannelHandlerContext;
import
io.netty.channel.ChannelInboundHandlerAdapter;
import
java.io.UnsupportedEncodingException;
public
class
ClientHandler
extends
ChannelInboundHandlerAdapter {
ChannelHandlerContext ctx;
/**
* tcp链路简历成功后调用
*/
@Override
public
void
channelActive(ChannelHandlerContext ctx)
throws
Exception {
this
.ctx = ctx;
}
public
boolean
sendMsg(String msg){
System.out.println(
"客户端发送消息:"
+msg);
byte
[] req = msg.getBytes();
ByteBuf m = Unpooled.buffer(req.length);
m.writeBytes(req);
ctx.writeAndFlush(m);
return
msg.equals(
"q"
)?
false
:
true
;
}
/**
* 收到服务器消息后调用
* @throws UnsupportedEncodingException
*/
@Override
public
void
channelRead(ChannelHandlerContext ctx, Object msg)
throws
UnsupportedEncodingException {
ByteBuf buf = (ByteBuf) msg;
byte
[] req =
new
byte
[buf.readableBytes()];
buf.readBytes(req);
String body =
new
String(req,
"utf-8"
);
System.out.println(
"服务器消息:"
+body);
}
/**
* 发生异常时调用
*/
@Override
public
void
exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
|
3、用于计算的工具类 。
1
2
3
4
5
6
7
8
9
10
11
|
package
com.anxpp.io.utils;
import
javax.script.ScriptEngine;
import
javax.script.ScriptEngineManager;
import
javax.script.ScriptException;
public
enum
Calculator {
Instance;
private
final
static
ScriptEngine jse =
new
ScriptEngineManager().getEngineByName(
"JavaScript"
);
public
Object cal(String expression)
throws
ScriptException{
return
jse.eval(expression);
}
}
|
4、测试 。
分别启动服务端和客户端,然后再客户端控制台输入表达式:
1
2
3
4
5
6
7
8
9
|
1+5+5+5+5+5
客户端发送消息:1+5+5+5+5+5
服务器消息:26
156158*458918+125615
客户端发送消息:156158*458918+125615
服务器消息:7.1663842659E10
1895612+555+5+5+5+5+5+5+5-5*4/4
客户端发送消息:1895612+555+5+5+5+5+5+5+5-5*4/4
服务器消息:1896197
|
可以看到服务端返回的结果.
查看服务端控制台:
1
2
3
4
|
服务器开启:9090
收到客户端消息:1+5+5+5+5+5
收到客户端消息:156158*458918+125615
收到客户端消息:1895612+555+5+5+5+5+5+5+5-5*4/4
|
5、更多 。
相关文章:
Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码) 。
本文例子以及Java BIO NIO AIO例子的源码Git地址:https://github.com/anxpp/Java-IO.git 。
后续会继续更新Netty相关内容,直到一个简陋的通讯服务器完成.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.
原文链接:http://blog.csdn.net/anxpp/article/details/52108238 。
最后此篇关于Java NIO框架Netty简单使用的示例的文章就讲到这里了,如果你想了解更多关于Java NIO框架Netty简单使用的示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我正在尝试使用 Netty 构建一个反向代理,并且我想保留一个到后端服务器的开放套接字池,而不是每个传入套接字都需要一个从反向代理到后端服务器的新套接字。 你能用 Netty 做到这一点吗?如何? 谢
从 Netty 3.5.x 到 Netty 4 性能提升了多少?有数据吗? 最佳答案 目前没有太大改进。不过,它的 GC 开销要少得多。一旦实现缓冲池,我相信吞吐量也会变得更好。目前,吞吐量增益约为
我正在尝试关闭与它建立连接的 Netty 服务器,但它只是挂起。这就是我所做的。 在一台机器上启动服务器,在另一台机器上启动客户端。 从客户端向服务器发送一条消息,我得到响应。 使用 Ctrl-C 关
doc说“每个轮子的默认滴答数(即轮子的大小)是 512。如果你要安排很多超时,你可以指定一个更大的值。” 这是否意味着默认情况下它只能处理 512 次超时?如果我想要 25 秒的 10 万次超时(对
我正在使用 netty 4.0.25Final 编写一个 netty HTTP 服务器。我需要根据 HTTP GET 请求中的一些参数在管道中添加各种处理程序。 pipeline.addLast(ne
我现在将 Netty 用于一些服务器端组件有一段时间了,我对此感到非常满意。因此,为了我自己的方便,我还想在客户端使用它,但我想保持小程序的占用空间(在这种情况下)尽可能小。我需要从 Netty 那里
有没有办法告诉 netty 停止监听和接受套接字上的新连接,但要完成当前连接上的任何正在进行的工作? 最佳答案 您可以关闭 ServerSocketChannel创建者 ChannelFactory
我用响应式(Reactive) mongo 创建了简单的 Webflux (kotlin) 应用程序。 Controller 有一个 GET 方法,即返回 Flow(来自一个集合的 2 个对象)。 我
我有一个新项目,我将第一次使用 Netty (v4.0.4)。我将拥有一个拥有数万个连接客户端的服务器。服务器将向这些客户端发送命令并应该接收响应。 查看 API 和在线示例,我不确定如何从服务器的角
与 boost.asio 不同,netty 没有类似 read 的方法。以下情况不方便:管理节点管理一些节点,客户端连接到管理节点以检索驻留在节点中的信息。当管理节点收到客户端的请求后,向对应的节点发
我正在编写一个应用程序,其中客户端和服务器都是使用 Netty 编写的,并且服务器应该(显然)同时支持多个客户端。我试图通过创建 1000 个客户端共享一个 EventLoopGroup 并在一台机器
如果我在 Netty 101 期间睡着了,请原谅我,但我想知道是否有一种“正确”的方式来等待 Netty 完成多步骤连接过程。假设我有一个应用程序,其过程如下所示: 打开实际连接。 执行 TLS 握手
将 Netty ChannelBuffer 转换为 String 就像在 ChannelBuffer 上调用 .toString(UTF_8) 一样简单。如何从字符串创建 ChannelBuffer?
在 Netty 3 中,我们可以这样做: Channel.setReadable(false); Channel.setReadable(true); 我读了: http://netty.io/new
我知道 Storm 现在运行在 Netty 上用于节点之间的通信? Apache Spark 是否也使用 Netty?如果真是这样,那么是以哪种方式? 最佳答案 Spark使用Akka Actor进行
很难说出这里问的是什么。这个问题是模棱两可的、模糊的、不完整的、过于宽泛的或修辞的,无法以目前的形式得到合理的回答。如需帮助澄清这个问题以便重新打开它,visit the help center .
我真的很困惑老板组的线程数。我想不出我们需要多个老板线程的情况。在 do we need more than a single thread for boss group? Netty 的创建者说,如
我已将其添加到我的管道中,并且 LoggingHandler 正在捕获其事件,但是由于事件系统从 Netty 3 更改为 4,我该如何处理这些事件,因为 IdleStateAwareUpstreamH
有没有办法在 channel 上保持状态。我正在编写一个聊天服务器,我想保留有关 channel 所属用户的信息。我在想也许 Channel 会提供一种方法来存储用户对象,但我看不到。有没有办法在不需
我有一个 netty channel ,我想在底层套接字上设置超时(默认设置为 0 )。 超时的目的是,如果 15 分钟内没有发生任何事情,则未使用的 channel 将被关闭。 虽然我没有看到任何配
我是一名优秀的程序员,十分优秀!