netty做文件服务器,快速搭建 netty服务器

前言

使用idea快速搭建基于maven的netty服务器项目

1.新建空白maven项目

file-new-project

选择maven空白项目,输入groupid和artifactid,一路点next

6c8ff6117e969da5c52f0226ee91cf3a.png

2.引入netty maven 依赖

pom.xml 文件加入netty-all 依赖

io.netty

netty-all

4.1.42.Final

3.服务器代码

tcp套接字server

创建ServerBootstrap,io模式为nio。同时自定义handler消息处理。

server代码:

public static void main(String[] args) throws InterruptedException {

//config the server

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

try{

ServerBootstrap b = new ServerBootstrap();

b.channel(NioServerSocketChannel.class)

.group(bossGroup,workerGroup)

.handler(new LoggingHandler(LogLevel.INFO))

.childHandler(new ChannelInitializer() {

protected void initChannel(SocketChannel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast(new LoggingHandler(LogLevel.INFO))

.addLast(new EchoServerHandler());

}

});

//start the server

ChannelFuture future = b.bind(8090).sync();

//wait until server is closed

future.channel().closeFuture().sync();

}finally {

//shut down the event loop to terminate all threads

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

handler代码:

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

ctx.write(msg);

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

ctx.flush();

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

cause.printStackTrace();

ctx.close();

}

}

http server

server 代码

public class HttpHelloWorldServer {

public static void main(String[] args) throws InterruptedException {

//config the server

NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

NioEventLoopGroup group = new NioEventLoopGroup();

try{

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup,group)

.channel(NioServerSocketChannel.class)

.handler(new LoggingHandler(LogLevel.INFO))

.childHandler(new ChannelInitializer(){

protected void initChannel(Channel ch) throws Exception {

ChannelPipeline p = ch.pipeline();

p.addLast(new HttpServerCodec())

.addLast(new HttpServerExpectContinueHandler())

.addLast(new HttpHelloWorldServerHandler());

}

});

//start the server

ChannelFuture future = b.bind(8090).sync();

System.out.println("open you browser and navigate to 127.0.0.1:8090");

//wait until server is closed

future.channel().closeFuture().sync();

}finally {

bossGroup.shutdownGracefully();

group.shutdownGracefully();

}

}

}

handler代码

public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler {

private static final byte[] CONTENT = "helloworld".getBytes();

protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

if (msg instanceof HttpRequest){

HttpRequest request = (HttpRequest) msg;

FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), OK,Unpooled.wrappedBuffer(CONTENT));

response.headers()

.set(CONTENT_TYPE, TEXT_PLAIN)

.setInt(CONTENT_LENGTH, response.content().readableBytes());

ChannelFuture f = ctx.write(response);

}

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

ctx.flush();

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

cause.printStackTrace();

ctx.close();

}

}

测试

首先测试tcp server。我们同时新建一个客户端与server进行交互:

client代码

public class EchoClient {

public static void main(String[] args) throws InterruptedException {

//config the client

EventLoopGroup group = new NioEventLoopGroup();

try{

Bootstrap bootstrap = new Bootstrap();

bootstrap.group(group)

.channel(NioSocketChannel.class)

.option(ChannelOption.TCP_NODELAY,true)

.handler(new ChannelInitializer() {

protected void initChannel(SocketChannel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast(new LoggingHandler(LogLevel.INFO))

.addLast(new EchoClientHandler());

}

});

//start the client

ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();

//wait until the connection is closed

future.channel().closeFuture().sync();

}finally {

//shut down the event loop to terminate all threads

group.shutdownGracefully();

}

}

}

clienhandler

public class EchoClientHandler extends ChannelInboundHandlerAdapter {

private final ByteBuf firstMsg;

public EchoClientHandler() {

this.firstMsg = Unpooled.wrappedBuffer("i am echo message".getBytes());

}

@Override

public void channelActive(ChannelHandlerContext ctx) throws Exception {

ctx.writeAndFlush(firstMsg);

}

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

ctx.write(msg);

}

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

TimeUnit.SECONDS.sleep(3);

ctx.flush();

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

cause.printStackTrace();

ctx.close();

}

}

先启动server,绑定端口8090。再启动client。连接server。

server日志:

43f46a7c5852b568eaab34df92294575.png

client 日志

2e4c8bebc6c8dd4cac15f2d69cc4e85b.png

可以看到客户端向服务器发送了一条消息,服务器收到消息原封不动回复客户端,客户端收到消息又原封不同回复服务器。像互相踢皮球一样。

然后再看下http server:

启动HttpHelloworldServer,然后打开浏览器访问http://127.0.0.1:8090。页面会出现helloworld的文字。

863473ddc9184ea453a50c920b911c9b.png

server日志

396bd05070df9998ab181abf9d6d31f3.png

最后

示例代码: my-netty-example

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值