Netty初始学习示例

1、服务端建立类TestServerHandler

代码:
package com.cora.api.client;

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;
 
 
public class TestServerHandler extends SimpleChannelUpstreamHandler {
 
    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
   
        ChannelBuffer acceptBuff = (ChannelBuffer) e.getMessage();
        String info = acceptBuff.toString("UTF-8");
//        info = acceptBuff.toString();
        if(info != null && !"".equals(info)) {
            System.out.println("Netty:"+info);
            ChannelBuffer sendBuff = ChannelBuffers.dynamicBuffer();
            sendBuff.writeBytes("Netty:Yes".getBytes());
            e.getChannel().write(sendBuff);
        }else {
            e.getChannel().write("_______服务端没有接收到信息!");
        }
        e.getChannel().close();
    }
 
    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause();
        e.getChannel().close();
    }
}
2、服务端建立类TestServer
代码:
package com.cora.api.client;

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;
 
public class TestServer {
 
    private final int port;
 
    public TestServer(int port) {
        this.port = port;
    }
 
    public void run() {
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));
 
//        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
//            public ChannelPipeline getPipeline() throws Exception {
//                return Channels.pipeline(new TestServerHandler());
//            }
//        });
        TestServerHandler handler = new TestServerHandler();
       
        bootstrap.getPipeline().addLast("handler", handler);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
 
        bootstrap.bind(new InetSocketAddress(port));
    }
 
    public static void main(String[] args) throws Exception {
        new TestServer(8080).run();
    }
}
3客户端建立类TestClientHandler
代码:
package com.cora.api.client;

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;
 
    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("I:" + firstMessage);
    }
 
    @Override 
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        ChannelBuffer acceptBuff = (ChannelBuffer) e.getMessage();
        String info = acceptBuff.toString("UTF-8");
//        info = acceptBuff.toString();
        System.out.println(info);
        e.getChannel().close();
    }
 
    @Override 
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause();
        e.getChannel().close();
    }
}
4、客户端建立类TestClient
代码:
package com.cora.api.client;

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() {
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(), 
                        Executors.newCachedThreadPool()));
 
//        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
//            public ChannelPipeline getPipeline() throws Exception {
//                return Channels.pipeline(
//                        new TestClientHandler(firstMessageSize));
//            }
//        });
       
        TestClientHandler handler = new TestClientHandler(firstMessageSize);

        bootstrap.getPipeline().addLast("handler", handler);
        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setOption("keepAlive", true);
 
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
 
        future.getChannel().getCloseFuture().awaitUninterruptibly();
 
        bootstrap.releaseExternalResources();
    }
 
    public static void main(String[] args) throws Exception {
        new TestClient("127.0.0.1", 8080, "Hello, Netty!我可以问一个问题吗?").run();
    }
}
5、示例代码见附件

你可能感兴趣的:(netty)