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. net core体系-web应用程序-1VS2017构建一个简单的web

    使用vs2017,添加一个新项目-asp.net core web应用程序. 结构如图, wwwroot放了网站的静态资源如css.js.image文件: appsetting.json是应用程序的配 ...

  2. zTree实战

    1.实体 public class UserDataZTreeVo { private String id; private String pid; private String name; priv ...

  3. Django分页(二)

    Django分页(二) 要求 .设定每页显示数据条数 # # .用户输入页码(第一页.第二页...) # # .设定显示多少页号 # # .获取当前数据总条数 # # .根据设定显示多少页号和数据总条 ...

  4. Python常用模块--re

    Python内部的re--传闻中的正则模块,是无数初学者心中的噩梦,几乎到了谈正则色变的地步. 1.正则是干什么的 正则表达式,又称规则表达式.(英语:Regular Expression,在代码中常 ...

  5. c++ <vector>学习

    https://www.cnblogs.com/mr-wid/archive/2013/01/22/2871105.html 具体参考上面博客,很详细,也是看他的.今天c++学习200%,项目开发0% ...

  6. Linux ubantu中安装虚拟/使用环境virtualenv以及python flask框架

    今天学习了python flask框架的安装过程以及使用案例,感觉网上讲的东西都没有从我们这种初学者的角度去考虑(哈哈),最后还是奉上心得: 1.安装virtualenv $ sudo apt-get ...

  7. Java性能调优zz

    写Java也有n年了,现在还是有不少的坏的代码习惯,也通过学习别人的代码学到了不少好的习惯.这篇文章主要是整理的资料.留给自己做个警戒,提示以后写代码的时候注意!在文章的后面,会提供整理的原材料下载. ...

  8. 一次ARP病毒排查

    XX公司网络卡断问题 1.  问题现象 2017年XX公司机关网络出现几次异常情况,并寻求内外部专家对异常情况进行诊断分析,均未找到原因,具体情况如下: 1.XX分公司机关网络IP地址为10.0.0. ...

  9. BZOJ.4446.[SCOI2015]小凸玩密室(树形DP)

    BZOJ LOJ 洛谷 (下面点亮一个灯泡就说成染色了,感觉染色比较顺口... 注意完全二叉树\(\neq\)满二叉树,点亮第一个灯泡\(\neq\)第一次点亮一号灯泡,根节点应该就是\(1\)... ...

  10. Ajax状态值及状态码整理

    1- AJAX状态值与状态码区别 AJAX状态值是指,运行AJAX所经历过的几种状态,无论访问是否成功都将响应的步骤,可以理解成为AJAX运行步骤.如:正在发送,正在响应等,由AJAX对象与服务器交互 ...