《精通并发与Netty》学习笔记(02 - 服务端程序编写)
上节我们介绍了开发netty项目所必需的开发环境及工具的使用,这节我们来写第一个netty项目
开发步骤
第一步:打开https://search.maven.org 找到netty依赖库

第二步:打开上节创建的项目,修改build.gradle文件如下图:

第三步:新建类com.ssy.netty.MyServer.class
package com.ssy.netty; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; /**
* netty作为长连接的服务器基于websoket,实现客户端与服务器端长连接。
*/
public class MyServer {
public static void main(String[] args) {
//负责接收客户端连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//处理连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup) // 绑定线程池
.channel(NioServerSocketChannel.class)
.childHandler(new ServerInitializer()); //绑定端口号
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
第四步:新建ServerInitializer类
package com.ssy.netty; import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec; /**
* 绑定客户端连接时候触发操作
*/
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//负载http 请求编码解码
pipeline.addLast("httpServerCodec",new HttpServerCodec());
//实际处理请求
pipeline.addLast("httpServerHandler",new HttpServerHandler());
}
}
第五步:
package com.ssy.netty; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil; /**
* 给客户端返回字符串信息"hello world"
*/
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
/**
* 该方法用于接收从客户端接收的信息
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if(msg instanceof HttpRequest){
//设置返回内容,ByteBuf是一个引用计数对象实现ReferenceCounted,他就是在有对象引用的时候计数+1,无的时候计数-1,当为0对象释放内存
ByteBuf content = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
//创建响应
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes()); ctx.writeAndFlush(response);
} }
}
第六步:启动MyServer服务端,命令行执行如下语句:

服务端返回:hello world
netty服务端程序到此介绍完毕,下节我们一起来写客户端程序。小伙伴们,让我们拭目以待吧!
《精通并发与Netty》学习笔记(02 - 服务端程序编写)的更多相关文章
- 《精通并发与Netty》学习笔记(03 - 客户端程序编写)
上节我们编写了netty服务端的程序,这节我们来写客户端程序 第一步:改造服务端程序为: (1)MyServer类: package com.ssy.netty.demo01; import io.n ...
- (二)Netty源码学习笔记之服务端启动
尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6129971.html 本文将不会对netty中每个点分类讲解,而是一个服务端启 ...
- Canal学习笔记(服务端)
canal服务端 canal服务端有两种运行模式,一种单机模式,一种HA运行模式(zk保证) 单机模式:同步的binlog节点信息保存在本地(/conf/{自定义分区文件夹}/),meta.dat H ...
- Netty学习4—NIO服务端报错:远程主机强迫关闭了一个现有的连接
1 发现问题 NIO编程中服务端会出现报错 Exception in thread "main" java.io.IOException: 远程主机强迫关闭了一个现有的连接. at ...
- 《精通并发与Netty》学习笔记(01 - netty介绍及环境搭建)
一.Netty介绍 Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序. ...
- 《精通并发与Netty》学习笔记(08 - netty4+springboot项目案例)
本节通过案例介绍springboot与netty的集成 第一步:新建Spring Initializr 项目 我这里选择Gradle项目,也可选择Maven项目 (注意:最好选择自己下载gradle, ...
- 《精通并发与Netty》学习笔记(06 - Apache Thrift使用简介)
一.概述 Apache Thrift 是 Facebook 实现的一种高效的.支持多种编程语言的远程服务调用的框架.Thrift是由Facebook开发的,并在2008年捐给了Apache基金会,成为 ...
- Netty学习笔记(二) 实现服务端和客户端
在Netty学习笔记(一) 实现DISCARD服务中,我们使用Netty和Python实现了简单的丢弃DISCARD服务,这篇,我们使用Netty实现服务端和客户端交互的需求. 前置工作 开发环境 J ...
- Netty学习笔记-入门版
目录 Netty学习笔记 前言 什么是Netty IO基础 概念说明 IO简单介绍 用户空间与内核空间 进程(Process) 线程(thread) 程序和进程 进程切换 进程阻塞 文件描述符 文件句 ...
随机推荐
- HDU 6060 - RXD and dividing | 2017 Multi-University Training Contest 3
/* HDU 6060 - RXD and dividing [ 分析,图论 ] | 2017 Multi-University Training Contest 3 题意: 给一个 n 个节点的树, ...
- 如何在 Laravel 项目中处理 Excel 文件
1.Laravel Excel Laravel Excel 是一款基于PHPExcel开发的Laravel框架专用的Excel/CSV 文件导入导出功能的扩展包,用起来的非常方便.它的Github地址 ...
- PHP实现省市区关键词搜索邮编
前两天做了一个项目, 其中有一个需求是根据用户输入的关键词查询邮编. 最开始设计的数据库结构是省市区分为三个字段, province, city, area, 但是在写代码实现的过程中发现, 用户只输 ...
- laravel Passport - Dingo/Api v2.0+Passport 实现 api 认证
第一部分: 安装passport 使⽤ Composer 依赖包管理器安装 Passport : composer require laravel/passport 接下来,将 Passport 的服 ...
- no suitable method found to override
no suitable method found to override http://bbs.csdn.net/topics/200001058
- [Luogu] 聪明的质监员
https://www.luogu.org/problemnew/show/P1314 满足单调性 所以,二分W,进行检验 #include <iostream> #include < ...
- plotly绘图
import plotly.plotly as plt import plotly.offline as pltoff from plotly.graph_objs import * # 生成折线图 ...
- python3 threading.Lock() 多线程锁的使用
import threadingimport time lock = threading.Lock() #创建锁 def fun(data): try: lock.acquire(True) #锁定 ...
- html页面之间相互传值
常见的在页面登录过后会获得一个token值然后页面跳转时传给下一个页面 sessionStorage.setItem("token",result.token);//传输token ...
- go面试
**1**.简述golang中make和new的区别 make用于内建类型(只能用于创建map.slice 和channel)的内存分配.并且返回一个有初始值(非零)的T类型,而不是*T. new用于 ...