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. SQLALCHEMY_TRACK_MODIFICATIONS adds significant异常的解决方法

  2. Kafka/Zookeeper集群的实现(二)

    [root@kafkazk1 ~]# wget http://mirror.bit.edu.cn/apache/zookeeper/zookeeper-3.4.12/zookeeper-3.4.12. ...

  3. tomcat-会话绑定

    会话保存 1) session  sticky source_ip                         原地址绑定 nginx: ip_hash haproxy: source lvs: ...

  4. PHP的swoole框架/扩展socket聊天示例

    PHP代码文件名 chat.php <?php //创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server(&qu ...

  5. Codeforces 982E Billiard 扩展欧几里德

    原文链接http://www.cnblogs.com/zhouzhendong/p/9055728.html 题目传送门 - Codeforces 928E 题意 一束与坐标轴平行或者成$45^\ci ...

  6. BZOJ1799 self 同类分布 数位dp

    BZOJ1799self 同类分布 去博客园看该题解 题意 给出a,b,求出[a,b]中各位数字之和能整除原数的数的个数. [约束条件]1 ≤ a ≤ b ≤ 10^18 题解 1.所有的位数之和&l ...

  7. python面试题之Python是如何进行内存管理的

    python内部使用引用计数,来保持追踪内存中的对象,Python内部记录了对象有多少个引用,即引用计数,当对象被创建时就创建了一个引用计数,当对象不再需要时,这个对象的引用计数为0时,它被垃圾回收. ...

  8. POJ 3169 Layout 【差分约束】+【spfa】

    <题目链接> 题目大意: 一些母牛按序号排成一条直线.有两种要求,A和B距离不得超过X,还有一种是C和D距离不得少于Y,问可能的最大距离.如果没有最大距离输出-1,如果1.n之间距离任意就 ...

  9. Django之认证系统

    Django之认证系统 cookie和session 1.cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此cookie就是在这样一个场景下诞 ...

  10. Springboot定时任务原理及如何动态创建定时任务

    一.前言 上周工作遇到了一个需求,同步多个省份销号数据,解绑微信粉丝.分省定时将销号数据放到SFTP服务器上,我需要开发定时任务去解析文件.因为是多省份,服务器.文件名规则.数据规则都不一定,所以要做 ...