需求:

  服务端:接收客户端请求,返回当前系统时间

  客户端:发起时间请求

服务端

package org.zln.netty.five.timer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 时间服务器服务端
* Created by sherry on 16/11/5.
*/
public class TimerServer {
/**
* 服务端绑定端口号
*/
private int PORT; public TimerServer(int PORT) {
this.PORT = PORT;
} /**
* 日志
*/
private static Logger logger = LoggerFactory.getLogger(TimerServer.class); public void bind() {
/*
NioEventLoopGroup是线程池组
包含了一组NIO线程,专门用于网络事件的处理
bossGroup:服务端,接收客户端连接
workGroup:进行SocketChannel的网络读写
*/
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
/*
ServerBootstrap:用于启动NIO服务的辅助类,目的是降低服务端的开发复杂度
*/
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)//配置TCP参数,能够设置很多,这里就只设置了backlog=1024,
.childHandler(new TimerServerInitializer());//绑定I/O事件处理类
logger.debug("绑定端口号:" + PORT + ",等待同步成功");
/*
bind:绑定端口
sync:同步阻塞方法,等待绑定完成,完成后返回 ChannelFuture ,主要用于通知回调
*/
ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();
logger.debug("等待服务端监听窗口关闭");
/*
closeFuture().sync():为了阻塞,服务端链路关闭后才退出.也是一个同步阻塞方法
*/
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
} finally {
logger.debug("优雅退出,释放线程池资源");
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
package org.zln.netty.five.timer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel; /**
* Created by sherry on 16/11/5.
*/
public class TimerServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline()
.addLast(new TimerServerHandler());
}
}
package org.zln.netty.five.timer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date; /**
* Handler主要用于对网络事件进行读写操作,是真正的业务类
* 通常只需要关注 channelRead 和 exceptionCaught 方法
* Created by sherry on 16/11/5.
*/
public class TimerServerHandler extends ChannelHandlerAdapter { /**
* 日志
*/
private Logger logger = LoggerFactory.getLogger(TimerServerHandler.class); @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//ByteBuf,类似于NIO中的ByteBuffer,但是更强大
ByteBuf reqBuf = (ByteBuf) msg;
//获取请求字符串
String req = getReq(reqBuf);
logger.debug("From:"+ctx.channel().remoteAddress());
logger.debug("服务端收到:" + req); if ("GET TIME".equals(req)){
String timeNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date());
String resStr = "当前时间:" + timeNow; //获取发送给客户端的数据
ByteBuf resBuf = getRes(resStr); logger.debug("服务端应答数据:\n" + resStr);
ctx.write(resBuf);
}else {
//丢弃
logger.debug("丢弃");
ReferenceCountUtil.release(msg);
} } /**
* 获取发送给客户端的数据
*
* @param resStr
* @return
*/
private ByteBuf getRes(String resStr) throws UnsupportedEncodingException {
byte[] req = resStr.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer(req.length);
//将字节数组信息写入到ByteBuf
pingMessage.writeBytes(req); return pingMessage;
} /**
* 获取请求字符串
*
* @param buf
* @return
*/
private String getReq(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
//将ByteByf信息写出到字节数组
buf.readBytes(con);
try {
return new String(con, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将消息发送队列中的消息写入到SocketChannel中发送给对方
logger.debug("channelReadComplete");
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//发生异常时,关闭 ChannelHandlerContext,释放ChannelHandlerContext 相关的句柄等资源
logger.error("exceptionCaught");
ctx.close();
}
}

客户端

package org.zln.netty.five.timer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* 时间服务器客户端
* Created by sherry on 16/11/5.
*/
public class TimerClient {
/**
* 日志
*/
private Logger logger = LoggerFactory.getLogger(TimerServer.class); private String HOST;
private int PORT; public TimerClient(String HOST, int PORT) {
this.HOST = HOST;
this.PORT = PORT;
} public void connect(){
//配置客户端NIO线程组
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY,true)
.handler(new TimerClientInitializer());
//发起异步连接操作
logger.debug("发起异步连接操作 - start");
ChannelFuture channelFuture = bootstrap.connect(HOST,PORT).sync();
logger.debug("发起异步连接操作 - end");
//等待客户端链路关闭
logger.debug("等待客户端链路关闭 - start");
channelFuture.channel().closeFuture().sync();
logger.debug("等待客户端链路关闭 - end");
} catch (InterruptedException e) {
logger.error(e.getMessage(),e);
}finally {
//优雅的关闭
eventLoopGroup.shutdownGracefully();
}
}
}
package org.zln.netty.five.timer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel; /**
* Created by sherry on 16/11/5.
*/
public class TimerClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimerClientHandler());
}
}
package org.zln.netty.five.timer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; /**
* Created by sherry on 16/11/5.
*/
public class TimerClientHandler extends ChannelHandlerAdapter { /**
* 日志
*/
private Logger logger = LoggerFactory.getLogger(TimerClientHandler.class); @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
logger.debug("客户端连接上了服务端"); //发送请求
ByteBuf reqBuf = getReq("GET TIME"); ctx.writeAndFlush(reqBuf);
} /**
* 将字符串包装成ByteBuf
* @param s
* @return
*/
private ByteBuf getReq(String s) throws UnsupportedEncodingException {
byte[] data = s.getBytes("UTF-8");
ByteBuf reqBuf = Unpooled.buffer(data.length);
reqBuf.writeBytes(data);
return reqBuf;
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
String resStr = getRes(byteBuf);
logger.debug("客户端收到:"+resStr);
} private String getRes(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}

关于ByteBuf的读写,面向的都是ByteBuf,所以对于 read,从ByteBuf中读出来,将数据给字节数组,对于写,将数据从字节数组写入到ByteBuf中

将字符串转化为ByteBuf,有更简单的方法

ByteBuf byteBuf = Unpooled.copiedBuffer(resStr.getBytes("UTF-8"));

Netty5-应答服务器的更多相关文章

  1. python网络编程【三】(网络服务器)

    建立一个服务器需要以下4步: 1.建立socket对象. 2.设置socket选项(可选的) 3.绑定到一个端口(同样,也可以是一个指定的网卡). 4.侦听连接. 下面代码片段可以实现这些功能: ho ...

  2. linux web服务器及LAMP动态网站平台搭建

    (vim补:)vim另存为:x,x w 目标文件路径vim批量删除x:x,x d Web服务:基于B/S架构的web通信服务端:支持HTTP协议的网页提供程序客户端:按标记规范显示网页的浏览器程序客户 ...

  3. 1. 通过DHCP服务器动态获取IP地址之后无法上网的解决方法

    故障:内网正常,在同一个局域网内的其它PC端通过DHCP获取IP地址并且可以正常上网. 1.通过wireshark抓包,使用ipconfig /renew时,wireshark内出现DHCP请求服务, ...

  4. linux服务器开发三(网络编程)

    网络基础 协议的概念 什么是协议 从应用的角度出发,协议可理解为"规则",是数据传输和数据的解释的规则. 假设,A.B双方欲传输文件.规定: 第一次,传输文件名,接收方接收到文件名 ...

  5. DNS服务器原理简述、搭建主/从DNS服务器并实现智能解析

    1. TLD:Top Level Domain 顶级域名 组织域:.com, .net, .org, .gov, .edu, .mil 国家域:.iq, .tw, .hk, .jp, .cn, ... ...

  6. Java Netty 4.x 用户指南

    问题 今天,我们使用通用的应用程序或者类库来实现互相通讯,比如,我们经常使用一个 HTTP 客户端库来从 web 服务器上获取信息,或者通过 web 服务来执行一个远程的调用. 然而,有时候一个通用的 ...

  7. 协议分析TMP

    最近闲来有事, 分析了一个非常低端(非常低端的意思是说你不应该对她是否能取代你现有的QQ客户端作任何可能的奢望,她只是一个实验性的东西)的手机QQ的协议, 是手机QQ3.0,      所用到的TCP ...

  8. TCP协议

    TCP是一个面向连接的协议,在发送数据之前,必须在双方之间建立一条连接. TCP首部 TCP数据封装在IP数据报中 TCP包首部 下面简单说明部分字段的作用: 端口号:通讯双方由IP地址和端口号标识. ...

  9. C#的HTTP协议中POST与GET的区别

    引言 HTTP协议我想任何IT人士都耳熟能详了,大家都能说出个所以然来.但是如果我问你HTTP协议的请求方法有哪些?POST与GET的差异?GET或POST传送数据量的大小有限制吗?HTTP响应的状态 ...

  10. Http基础

    Http基础 这篇文章是讲Android网络请求的先导文章,主要讲Http工作流程,请求报文和响应报文的格式,以及GET和POST方法的具体含义. Http工作流程 HTTP是一个客户端和服务器端请求 ...

随机推荐

  1. 关于一个js连续赋值问题之我见(词略穷,见谅)

    前几天在搜索面试题时发现了这么一段代码,执行完后感觉完全不与所想的一样 var a = { n : 1 }; var b = a; a.x = a = {n : 2}; console.log(a.x ...

  2. abap 选择屏幕事件AT SELECTION-SCREEN

    AT SELECTION-SCREEN (1).其实就像一个FORM,所以在这个事件里声明的变量都是局部变量. (2).根据SY-UCOMM这个系统变量可以判断用户的命令 (3).在这个事件里响应的是 ...

  3. .NET下Excel报表的打印

    说明:这是一个实验的小例子,在实际项目中使用时,一般Object[,] 对象的数据来源于数据库. 1. 实验环境 开发平台:Visual Studio 2010 测试模板:JBtest Excel:O ...

  4. iOS开发之网络数据解析--中文输出

    对于服务器返回的数据,解析之后直接打印,如果数据中原本有中文,可能会出现中文乱码的结果: 为了避免这个问题,可以通过类别来重写系统和打印相关的方法. 步骤: 1.新建文件名:Foundation+Lo ...

  5. 《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <五> NSDicionary + NSMutableDictionary

    int main(int argc, const char * argv[]) { @autoreleasepool { //字典, 存储的内存不是连续的 用key和value进行对应(键值) //k ...

  6. Weblogic11g下调WebService出现的一系列问题

    Weblogic11g下调WebService出现的一系列问题 今天在远程测试机上测试前天写的调用WebService接口方法,遇到的问题还真多啊! 首先说明一下weblogic加载jar包的顺序: ...

  7. iphone,pad等真机不被xcode识别,解决方法

    问题现象:xcode 的项目在进行真机调试时,xcode不能识别真机, 调测情况分析: 1 设备正常,itunes 能够识别 2 在apple developer 中创建项目的Provisioning ...

  8. Effective Java 10 Always override toString() method

    Advantage Provide meaningful of an object info to client. Disadvantage Constrain the ability of chan ...

  9. Linux 环境变量的配置

    一. 环境变量相关的几个配置文件(针对bash): 1.  /etc/profile 系统环境变量配置文件:针对整个系统的所有用户生效,系统启动后用户第一次登陆时,此文件被执行,并从/etc/prof ...

  10. BI Project Managerment

    Design doc is the meta data of the code. The project management plan is crucial to your project sinc ...