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 ...
随机推荐
- seafile增加邮件服务功能
这个很简单哈,直接上配置.此处我用的163邮箱 vim /opt/seafile/conf/seahub_settings.py ### 163邮箱配置测试 ### EMAIL_USE_SSL = F ...
- 移动端上拉加载下拉刷新插件-mescroll.js插件
官网地址是:http://www.mescroll.com // 初始化mescroll function initMeScroll() { //创建MeScroll对象,内部已默认开启下拉刷新,自动 ...
- Python交互图表可视化Bokeh:2. 辅助参数
图表辅助参数设置 辅助标注.注释.矢量箭头 参考官方文档:https://bokeh.pydata.org/en/latest/docs/user_guide/annotations.html#col ...
- day10.函数,函数的参数
函数的思维导图: 老师的笔记 昨天内容概括 #组长:默写统一交给组长 #不建议看视频 #上课敲过的所有的例子 # 1.看一遍.看能不能看懂 # 2.给每一道题起一个名字或者一句描述 # 3.看着文字, ...
- python基础篇_002_基础数据类型
Python基础数据类型 1.int # int 用于计算 num = 3 # int 与其他数据类型转换 int_to_str = str(num) # 数字加引号 print(int_to_str ...
- Decision Trees:机器学习根据大量数据,已知年龄、收入、是否上海人、私家车价格的人,预测Ta是否有真实购买上海黄浦区楼房的能力—Jason niu
from sklearn.feature_extraction import DictVectorizer import csv from sklearn import tree from sklea ...
- gradle上传本地文件到远程maven库(nexus服务器)
自定义aar-upload.gradle文件 artifacts { archives file('./build/outputs/aar/Lib_ads-baidu-debug.aar') } up ...
- 转载:ThreadPoolExecutor 源码阅读
前言 之前研究了一下如何使用ScheduledThreadPoolExecutor动态创建定时任务(Springboot定时任务原理及如何动态创建定时任务),简单了解了ScheduledThreadP ...
- linux 学习笔记三
用户管理篇章 useradd 建立用户 一般用法 #useradd mysql 含义 创建 mysql用户 特殊用户 > #useradd -d /usr/cjh -m cjh 含义 创建 cj ...
- linux 学习笔记 ftp
server with sites set up for download files sometimes provide an anonymous ftp account 数据传输 ftp 192. ...