【初学与研发之NETTY】简介与HelloWorld之例(netty3)

7 篇文章 0 订阅

Netty是什么?

Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。

 

特性有哪些?

 

1、基于灵活的、可扩展的事件驱动,API适用不同的协议(阻塞和非阻塞),支持TCP和UDP的socket服务开发。

2、高并发、低延时、高吞吐量。

3、简单、安全、可靠、易用。

 

如何使用?

 

废话不多说,请看简单的HelloWorld示例:

服务端:

package example.echo;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

/**
 * Echoes back any received data from a client.
 */
public class TestServer {

    private final int port;

    public TestServer(int port) {
        this.port = port;
    }

    public void run() {
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new TestServerHandler());
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
    }

    public static void main(String[] args) throws Exception {
      
        new TestServer(8080).run();
    }
}

服务端处理Handler类:

package example.echo;

import java.nio.charset.Charset;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;


/**
 * Handler implementation for the echo server.
 */
public class TestServerHandler extends SimpleChannelUpstreamHandler {

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        // Send back the received message to the remote peer.
    	ChannelBuffer acceptBuff = (ChannelBuffer) e.getMessage();
    	String info = acceptBuff.toString(Charset.defaultCharset());
    	if(info != null && !"".equals(info)) {
    		System.out.println("_______服务端接收到>>>>>"+info);
    		ChannelBuffer sendBuff = ChannelBuffers.dynamicBuffer();
        	sendBuff.writeBytes("_______服务端已接收到信息!".getBytes());
            e.getChannel().write(sendBuff);
    	} else {
    		e.getChannel().write("_______服务端没有接收到信息!");
    	}
    	e.getChannel().close();
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        // Close the connection when an exception is raised.
    	e.getCause();
        e.getChannel().close();
    }
}


客户端:

package example.echo;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class TestClient {

    private final String host;
    private final int port;
    private final String firstMessageSize;

    public TestClient(String host, int port, String firstMessageSize) {
        this.host = host;
        this.port = port;
        this.firstMessageSize = firstMessageSize;
    }

    public void run() {
        // Configure the client.
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        new TestClientHandler(firstMessageSize));
            }
        });

        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

        // Wait until the connection is closed or the connection attempt fails.
        future.getChannel().getCloseFuture().awaitUninterruptibly();

        // Shut down thread pools to exit.
        bootstrap.releaseExternalResources();
    }

    public static void main(String[] args) throws Exception {
        
        new TestClient("127.0.0.1", 8080, "HelloWorld, Welcome to netty!").run();
    }
}


客户端处理Handler类:

package example.echo;

import java.nio.charset.Charset;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class TestClientHandler extends SimpleChannelUpstreamHandler {

    private final String firstMessage;

    /**
     * Creates a client-side handler.
     */
    public TestClientHandler(String firstMessageSize) {
        firstMessage = firstMessageSize;
    }

    @Override
    public void channelConnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) {
    	ChannelBuffer sendBuff = ChannelBuffers.dynamicBuffer();
    	sendBuff.writeBytes(firstMessage.getBytes());
    	
        e.getChannel().write(sendBuff);
        System.out.println("_____客户端发送信息完成!");
    }

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        // Send back the received message to the remote peer.
    	ChannelBuffer acceptBuff = (ChannelBuffer) e.getMessage();
    	String info = acceptBuff.toString(Charset.defaultCharset());
    	System.out.println(info);
    	e.getChannel().close();
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        // Close the connection when an exception is raised.
    	e.getCause();
        e.getChannel().close();
    }
}


运行服务端以及客户端后的控制台输出结果:

服务端:

_______服务端接收到>>>>>HelloWorld, Welcome to netty!

 

客户端:

_____客户端发送信息完成!
_______服务端已接收到信息!

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值