netty4.0 Server和Client的通信
netty4.0 Server和Client的通信
创建一个maven项目
添加Netty依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.16.Final</version>
</dependency>
Server端开发
public class HelloServer {
public void start(int port) {
ServerBootstrap serverBootstrap = new ServerBootstrap();//注意和 client 的区别
EventLoopGroup boosGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
serverBootstrap.group(boosGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);//注意和 client 端的区别,client 端是 NioSocketChannel
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HelloServerInHandler());
}
});
serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
try {
// 绑定端口,开始接收进来的连接
ChannelFuture f = serverBootstrap.bind(port).sync();
// 等待服务器 socket 关闭 。
// 在这个例子中,这不会发生,但你可以优雅地关闭你的服务器。
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
HelloServer helloServer = new HelloServer();
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
helloServer.start(port);
}
}
server 消息处理
@ChannelHandler.Sharable
public class HelloServerInHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try{
ByteBuf inMsg = (ByteBuf) msg;
byte[] bytes = new byte[inMsg.readableBytes()];
inMsg.readBytes(bytes);
String inStr = new String(bytes);
System.out.println("client send msg: " + inStr);
String response = "i am ok!";
ByteBuf outMsg = ctx.alloc().buffer(4 * response.length());
outMsg.writeBytes(response.getBytes());
ctx.writeAndFlush(outMsg);
}finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
super.channelReadComplete(ctx);
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
ctx.close();
}
}
client 开发
public class HelloClient {
public void connect(String host, int port) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap(); //注意和 server 的区别
bootstrap.group(eventLoopGroup);
bootstrap.channel(NioSocketChannel.class);//注意和 server 端的区别,server 端是 NioServerSocketChannel
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HelloClientIntHandler());
}
});
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
try {
// Start the client.
ChannelFuture future = bootstrap.connect(host, port).sync();
// 等待服务器 socket 关闭 。
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
HelloClient client = new HelloClient();
client.connect("127.0.0.1", 8080);
}
}
client 消息处理
public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
// 连接成功后,向server发送消息
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("connected server. start send msg.");
String msg = "r u ok?";
ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
encoded.writeBytes(msg.getBytes());
ctx.writeAndFlush(encoded);
}
// 接收server端的消息,并打印出来
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf result = (ByteBuf) msg;
byte[] serverMsg = new byte[result.readableBytes()];
result.readBytes(serverMsg);
System.out.println("Server said:" + new String(serverMsg));
} finally {
ReferenceCountUtil.release(msg);
}
}
}
测试
分别启动server端和client端
server端会输出如下内容:
client send msg: r u ok?
client端会输出如下内容:
Server said:i am ok!
netty4.0 Server和Client的通信的更多相关文章
- (填坑系列) 用aio写server与client进行通信的坑
最近闲来无事,就估摸着自己写个“服务注册中心”来玩,当然因为是个人写的,所以一般都是简洁版本. 代码地址在:https://gitee.com/zhxs_code/my-service-registe ...
- Netty4.0学习笔记系列之一:Server与Client的通讯
http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...
- Android简单实现Socket通信,client连接server后,server向client发送文字数据
案例实现的是简单的Socket通信,当client(Androidclient)连接到指定server以后,server向client发送一句话文字信息(你能够拓展其他的了) 先看一下服务端程序的实现 ...
- Netty4.0.24.Final 版本中 IdleStateHandler 使用时的局限性
使用Netty在客户端和服务端建立通讯通道,一般来说,一个连接可能很久没有访问,由于各种各样的网络问题导致连接已经失效,客户端再次发送请求时会产生连接异常. 基于这个原因,需要在客户端和服务端之间建立 ...
- swoole学习(二)----搭建server和client
1.搭建server 1.1搭建server.php 1.搭建websocket服务器,首先建立 server.php 文件, <?php $server = new swoole_websoc ...
- ESP8266开发之旅 网络篇⑦ TCP Server & TCP Client
授人以鱼不如授人以渔,目的不是为了教会你具体项目开发,而是学会学习的能力.希望大家分享给你周边需要的朋友或者同学,说不定大神成长之路有博哥的奠基石... QQ技术互动交流群:ESP8266&3 ...
- server and client
server: using System;using System.Collections.Generic;using System.Linq;using System.Text;using Syst ...
- C Socket Programming for Linux with a Server and Client Example Code
Typically two processes communicate with each other on a single system through one of the following ...
- 浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路
文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6627260 在前面一篇文章浅谈Service ...
随机推荐
- img 标签的 usemap 属性
<img src="1.gif" alt="Planets" usemap="#Map"/> <map name=&quo ...
- BZOJ3437 小P的牧场 动态规划 斜率优化
原文链接http://www.cnblogs.com/zhouzhendong/p/8696321.html 题目传送门 - BZOJ3437 题意 给定两个序列$a,b$,现在划分$a$序列. 被划 ...
- 013 mysql中find_in_set()函数的使用
在工作中遇见过,对于新知识,在这里写一写文档. 1.作用 举个例子,也许不理解,在看完后面的SQL示例,再来看就明白了: 有个文章表里面有个type字段,它存储的是文章类型,有 1头条.2推荐.3热点 ...
- 初窥Java之二
一.java中存在三大注释: 第一大注释: 单行注释 一般用于信息量比较少的地方 第二大注释: 多行注释 一般用于信息比较多的地方 多行注释注意事项:1.多行注释的开始行与结尾行不能写注释 ...
- POJ 2763 Housewife Wind 【树链剖分】+【线段树】
<题目链接> 题目大意: 给定一棵无向树,这棵树的有边权,这棵树的边的序号完全由输入边的序号决定.给你一个人的起点,进行两次操作: 一:该人从起点走到指定点,问你这段路径的边权总和是多少. ...
- Linux学习之后台任务与定时任务(二十)
Linux学习之后台任务与定时任务 目录 后台任务 把进程放入后台 查看后台任务 将后台暂停的工作恢复到前台执行 将后台暂停的工作恢复到后台执行 定时任务 手动启动服务 将服务设置为自启动 用户的co ...
- P2661 信息传递
P2661 信息传递dfs求最小环,要加时间戳,记录这个点是哪一次被dfs到的.] #include<iostream> #include<cstdio> #include&l ...
- Splay的初步学习
具体是啥,qwq 有时间再补吧,贴一下代码: #include<iostream> #include<cstdio> #include<cstring> #incl ...
- [洛谷P1886]滑动窗口 (单调队列)(线段树)
---恢复内容开始--- 这是很好的一道题 题目描述: 现在有一堆数字共N个数字(N<=10^6),以及一个大小为k的窗口. 现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的 ...
- spring boot默认访问静态资源
演示spring boot默认可以直接访问静态资源的2种方法: 第一种:在src/main/resources资源目录下创建一个名为"static"的文件夹(该文件夹的名称是规定死 ...