Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from ipipman:master #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 2 commits into Mu-L:master from ipipman:master
Jan 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion springboot-netty-sample/pom.xml
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,21 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-netty-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-netty-sample</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<maven.version>1.8</maven.version>
</properties>


<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -27,6 +31,13 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- 引入Netty依赖 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.39.Final</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.ipman.netty.springboot.sample.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
* Created by ipipman on 2022年1月19日.
*
* @version V1.0
* @Package com.ipman.netty.springboot.sample.echo
* @Description: (用一句话描述该文件做什么)
* @date 2022年1月19日 9:26 下午
*/
public class EchoClient {

public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup();
EchoClientHandler clientHandler = new EchoClientHandler();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(clientHandler);
}
});
// 连接server端
ChannelFuture cf = b.connect("127.0.0.1", 8090).sync();
// 等待连接关闭
cf.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.ipman.netty.springboot.sample.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
* Created by ipipman on 2022年1月19日.
*
* @version V1.0
* @Package com.ipman.netty.springboot.sample.echo
* @Description: (用一句话描述该文件做什么)
* @date 2022年1月19日 9:26 下午
*/
@Sharable
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

private final ByteBuf firstMsg;

public EchoClientHandler() {
firstMsg = Unpooled.wrappedBuffer("Hello Codeing".getBytes(StandardCharsets.UTF_8));
}

/**
* 通道活跃时
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 第一次传输
ctx.writeAndFlush(firstMsg);
}

/**
* 读取数据时
*
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.write(msg);
}

/**
* 读取完毕时
*
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// 延迟3秒
TimeUnit.SECONDS.sleep(3);
ctx.flush();
}

/**
* 捕获到异常时
*
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.ipman.netty.springboot.sample.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
* Created by ipipman on 2022年1月19日.
*
* @version V1.0
* @Package com.ipman.netty.springboot.sample.http
* @Description: (用一句话描述该文件做什么)
* @date 2022年1月19日 9:09 下午
*/
public class EchoServer {

public static void main(String[] args) {
// 创建Server端
EventLoopGroup workGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(workGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(serverHandler);
}
});
// 绑定端口
ChannelFuture f = b.bind(8090).sync();
// 等待连接关闭
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 关闭所有线程
workGroup.shutdownGracefully();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.ipman.netty.springboot.sample.echo;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
* Created by ipipman on 2022年1月19日.
*
* @version V1.0
* @Package com.ipman.netty.springboot.sample.http
* @Description: (用一句话描述该文件做什么)
* @date 2022年1月19日 9:11 下午
*/
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {


/**
* 读取
*
* @param ctx
* @param msg
* @throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.write(msg);
}

/**
* 读取完毕时
*
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}

/**
* 抓住异常
*
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.ipman.netty.springboot.sample.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
* Created by ipipman on 2022年1月19日.
*
* @version V1.0
* @Package com.ipman.netty.springboot.sample.http
* @Description: (用一句话描述该文件做什么)
* @date 2022年1月19日 10:00 下午
*/
public class HttpServer {

public static void main(String[] args) {
// 主从模式
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();

try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// HTTP 模式
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
p.addLast(new HttpServerExpectContinueHandler());
p.addLast(new HttpServerHandler());
}
});
ChannelFuture ch = b.bind(8099).sync();

System.out.println("Open Http Server : http://127.0.0.1:8099");
ch.channel().closeFuture().sync();

} catch (Exception ex) {
ex.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.ipman.netty.springboot.sample.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN;


/**
* Created by ipipman on 2022年1月19日.
*
* @version V1.0
* @Package com.ipman.netty.springboot.sample.http
* @Description: (用一句话描述该文件做什么)
* @date 2022年1月19日 9:50 下午
*/
@Sharable
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

private static final byte[] CONTEXT = "hello coding".getBytes(StandardCharsets.UTF_8);

/**
* 当读取完毕时
*
* @param ctx
* @throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK, Unpooled.wrappedBuffer(CONTEXT));
response.headers()
.set(CONTENT_TYPE, TEXT_PLAIN)
.set(CONTENT_LENGTH, response.content().readableBytes());

ChannelFuture f = ctx.write(response);
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}

AltStyle によって変換されたページ (->オリジナル) /