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的通信的更多相关文章

  1. (填坑系列) 用aio写server与client进行通信的坑

    最近闲来无事,就估摸着自己写个“服务注册中心”来玩,当然因为是个人写的,所以一般都是简洁版本. 代码地址在:https://gitee.com/zhxs_code/my-service-registe ...

  2. Netty4.0学习笔记系列之一:Server与Client的通讯

    http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...

  3. Android简单实现Socket通信,client连接server后,server向client发送文字数据

    案例实现的是简单的Socket通信,当client(Androidclient)连接到指定server以后,server向client发送一句话文字信息(你能够拓展其他的了) 先看一下服务端程序的实现 ...

  4. Netty4.0.24.Final 版本中 IdleStateHandler 使用时的局限性

    使用Netty在客户端和服务端建立通讯通道,一般来说,一个连接可能很久没有访问,由于各种各样的网络问题导致连接已经失效,客户端再次发送请求时会产生连接异常. 基于这个原因,需要在客户端和服务端之间建立 ...

  5. swoole学习(二)----搭建server和client

    1.搭建server 1.1搭建server.php 1.搭建websocket服务器,首先建立 server.php 文件, <?php $server = new swoole_websoc ...

  6. ESP8266开发之旅 网络篇⑦ TCP Server & TCP Client

    授人以鱼不如授人以渔,目的不是为了教会你具体项目开发,而是学会学习的能力.希望大家分享给你周边需要的朋友或者同学,说不定大神成长之路有博哥的奠基石... QQ技术互动交流群:ESP8266&3 ...

  7. server and client

    server: using System;using System.Collections.Generic;using System.Linq;using System.Text;using Syst ...

  8. 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 ...

  9. 浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6627260 在前面一篇文章浅谈Service ...

随机推荐

  1. LAMP编译安装部分

    # yum install -y apr-devel apr-util-devel pcre-devel # wget http://mirror.bit.edu.cn/apache/httpd/ht ...

  2. HDU5117 Fluorescent 期望 计数 状压dp 动态规划

    原文链接https://www.cnblogs.com/zhouzhendong/p/HDU5117.html 题目传送门 - HDU5117 题意 $T$ 组数据. 给你 $n$ 盏灯 ,$m$ 个 ...

  3. Java中byte、short、char、int、long运算时自动类型转化问题

    -------------------------------------------------------------------------------------------------- ★ ...

  4. 20165235 祁瑛 2018-4 《Java程序设计》第九周学习总结

    20165235 祁瑛 2018-4 <Java程序设计>第九周学习总结 教材学习内容总结 URL类 UR类是java.net包中的一个重要类,使用URL创建的对象的应用程序称作称作客户端 ...

  5. 怎样将一个Long类型的数据转换成字节数组

    直接上代码: //先写进去 long n = 1000000L; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutpu ...

  6. json 对象和json字符串

    转载至  http://www.cnblogs.com/cstao110/p/3762056.html JSON字符串与JSON对象的区别 Q:什么是"JSON字符串",什么是&q ...

  7. oracle中计算百分比,并同时解决小数点前0不显示的问题

    select a.catalog_name,decode(substr(trunc((a.s/b.count2),4)*100||'%',0,1),'.',replace(trunc((a.s/b.c ...

  8. CentOS系统找不到setup命令工具的解决方法

    如果你的CentOS系统中没有setup命令,很有可能是因为你安装CentOS系统时采用了最小化安装(minimal).这时,你执行setup命令时,就会报错: 错误信息: 1[root@localh ...

  9. Windows10系统网络连接问题

    Thinkpad笔记本Windows10系统突然遇到网络连接问题: 问题:今天同事遇到一个WiFi连接问题,ThinkPad笔记本在公司和家里面都无法连接WiFi 寻找问题: 1.检查硬件问题 首先我 ...

  10. HDU 5178 pairs【二分】||【尺取】

    <题目链接> 题目大意: 给定一个整数序列,求出绝对值小于等于k的有序对个数. 解题分析: $O(nlong(n))$的二分很好写,这里就不解释了.本题尺取$O(n)$也能做,并且效率很不 ...