Netty框架是基于事件机制的,简单说,就是发生什么事,就找相关处理方法。
依赖的pom
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty</artifactId>
<version>3.9.0.Final</version>
</dependency>
服务器端
package com.netty;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
/**
* Created by IntelliJ IDEA.
* User: wan
* Date: 14-2-23
* Time: 下午1:34
*/
public class HelloServer {
public static void main(String args[])throws Exception{
// Server服务启动器
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// 设置一个处理客户端消息和各种消息事件的类(Handler)
bootstrap
.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline()
throws Exception {
return Channels.pipeline(new HelloServerHandler());
}
});
// 开放8000端口供客户端访问。
bootstrap.bind(new InetSocketAddress(8000));
}
private static class HelloServerHandler extends SimpleChannelHandler {
/**
* 当有客户端绑定到服务端的时候触发,打印"Hello world, I'm server."
*
* @alia OneCoder
* @author lihzh
*/
@Override
public void channelConnected(
ChannelHandlerContext ctx,
ChannelStateEvent e) {
System.out.println("Hello world, I'm server.");
}
}
}
客户端
package com.netty;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
/**
* Created by IntelliJ IDEA.
* User: wan
* Date: 14-2-23
* Time: 下午1:59
*/
public class HelloClient {
public static void main(String args[]) {
// Client服务启动器
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// 设置一个处理服务端消息和各种消息事件的类(Handler)
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new HelloClientHandler());
}
});
// 连接到本地的8000端口的服务端
bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
}
private static class HelloClientHandler extends SimpleChannelHandler {
/**
* 当绑定到服务端的时候触发,打印"Hello world, I'm client."
*
* @alia OneCoder
* @author lihzh
*/
@Override
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) {
System.out.println("Hello world, I'm client.");
}
}
}