菜鸟Java使用Netty

原文地址为: 菜鸟Java使用Netty

下载下来,搜索半天,如何使用Netty。。。。。。。。。。。网上找不到一篇类似的文章。对新手真是巨大的创伤啊!


还下载了Maven。现在还不知道这个东西干嘛的。好像对我使用Natty一点帮助都没有。



下载完,解压至某指定目录。

然后引入它的包即可


打开两个Eclipse

一个写一个服务器,一个写一个客户端 



服务器结果如下:

此四步用于引入Netty的包。

客户端亦如此




EchoServer.java 代码为:


/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/


package netty.echo.handler;

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

@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("channelActive!!!!!!!!!!!");
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("channelRead!!!!!!!!!!!!!!!!!!!!!!!");

ByteBuf buf = (ByteBuf)msg;
//System.out.println(buf.);
ctx.write(msg);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}



EchoServerHandler.java 代码为:


/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/


package netty.echo.handler;

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

@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("channelActive!!!!!!!!!!!");
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("channelRead!!!!!!!!!!!!!!!!!!!!!!!");

ByteBuf buf = (ByteBuf)msg;
//System.out.println(buf.);
ctx.write(msg);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}





             客户端               





EchoClient.java 代码为:


/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/


package netty.echo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

public final class EchoClient {

static final boolean SSL = System.getProperty("ssl") != null;
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));

public static void main(String[] args) throws Exception {
// Configure SSL.git
final SslContext sslCtx = null;

// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
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();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
}
// p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new EchoClientHandler());
}
});

// Start the client.
ChannelFuture f = b.connect(HOST, PORT).sync();

// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
group.shutdownGracefully();
}
}
}




EchoClientHandler.java 代码为:


/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package netty.echo.client;

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

/**
* Handler implementation for the echo client. It initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server.
*/
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

private final ByteBuf firstMessage;

/**
* Creates a client-side handler.
*/
public EchoClientHandler() {
firstMessage = Unpooled.buffer(EchoClient.SIZE);
for (int i = 0; i < firstMessage.capacity(); i ++) {
firstMessage.writeByte((byte) i);
}
}

@Override
public void channelActive(ChannelHandlerContext ctx) {
//ctx.writeAndFlush(firstMessage);
String x = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
firstMessage.writeBytes(x.getBytes());
ctx.writeAndFlush(firstMessage);
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}





运行结果:


服务器启动为Java Application类型,




客户端启动后,服务器的反应:






http://blog.csdn.net/suifeng3051/article/details/25238243

     这里有一个形象的比喻来形容Netty客户端和服务器端的交互模式,

比如把你比作一个Client,把山比作一个Server,你走到山旁,就是和山建立了链接,

你向山大喊了一声,就代表向山发送了数据,你的喊声经过山的反射形成了回声,这个回声就是服务器的响应数据。如果你离开,就代表断开了链接,当然你也可以再回来。

好多人可以同时向山大喊,他们的喊声也一定会得到山的回应。



官方文档:


http://netty.io/wiki/user-guide-for-4.x.html#wiki-h3-17


Netty4.x中文教程系列(一) 目录及概述 - Tiny&zzh - 博客园

 http://www.cnblogs.com/zou90512/p/3492287.html



[Android初级]android与netty4初体验 - 消失的天空 - 博客频道 - CSDN.NET

 http://blog.csdn.net/jan_s/article/details/43702569



Netty4详解三:Netty架构设计 - Heaven Wang 的专栏 - 博客频道 - CSDN.NET  http://blog.csdn.net/suifeng3051/article/details/28861883?utm_source=tuicool&utm_medium=referral Netty4详解


转载请注明本文地址: 菜鸟Java使用Netty

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/80876019
今日推荐