Person.java
package yang.netty.test;
public class Person {
private String name;
private int age;
private double salary;
public Person(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Persons [name=" + name + ", age=" + age + ", salary=" + salary
+ "]";
}
}
NettyServer.java
package yang.netty.test;
import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
class PersonServerDecoder extends FrameDecoder {
private final ChannelBuffer buffer = dynamicBuffer();// 默认分配256
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
ChannelBuffer channelBuffer) throws Exception {
if (channelBuffer.readable()) {
// 将channelBuffer中的数据转移的buffer中
channelBuffer.readBytes(buffer, channelBuffer.readableBytes());
}
int namelength = buffer.readInt();
String name = new String(buffer.readBytes(namelength).array(), "GBK");
int age = buffer.readInt();
double salary = buffer.readDouble();
Person person = new Person(name, age, salary);
return person;
}
}
//修改年龄并将结果返回给Client
class PersonServerEncoder extends SimpleChannelHandler {
private final ChannelBuffer buffer = dynamicBuffer();
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
Person person = (Person) e.getMessage();
buffer.writeInt(person.getName().getBytes("GBK").length);
buffer.writeBytes(person.getName().getBytes("GBK"));
buffer.writeInt(person.getAge() + 10);
buffer.writeDouble(person.getSalary());
Channels.write(ctx, e.getFuture(), buffer);
}
}
class PersonServerHandler extends SimpleChannelHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
Person person = (Person) e.getMessage();
System.out.println("Recevied Message: " + person);
String response = "OK";
e.getChannel().write(response);
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("Unexpected exception from upstream."
+ e.getCause());
e.getChannel().close();
}
}
public class NettyServer {
public void testServer() {
ChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new PersonServerDecoder());
// pipeline.addLast("encoder", new PersonServerEncoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new PersonServerHandler());
return pipeline;
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.bind(new InetSocketAddress("localhost", 3333));
System.out.println("Server is on ....");
}
}
NettyClient.java
package yang.netty.test;
import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.jboss.netty.handler.codec.string.StringDecoder;
class PersonClientDecoder extends FrameDecoder {
private final ChannelBuffer buffer = dynamicBuffer();
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
ChannelBuffer channelBuffer) throws Exception {
if (channelBuffer.readable()) {
// 将channelBuffer中的数据转移的buffer中
channelBuffer.readBytes(buffer, channelBuffer.readableBytes());
}
int namelength = buffer.readInt();
String name = new String(buffer.readBytes(namelength).array(), "GBK");
int age = buffer.readInt();
double salary = buffer.readDouble();
Person person = new Person(name, age, salary);
return person;
}
}
class PersonClientEncoder extends SimpleChannelHandler {
private final ChannelBuffer buffer = dynamicBuffer();
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
Person person = (Person) e.getMessage();
buffer.writeInt(person.getName().getBytes("GBK").length);
buffer.writeBytes(person.getName().getBytes("GBK"));
buffer.writeInt(person.getAge());
buffer.writeDouble(person.getSalary());
Channels.write(ctx, e.getFuture(), buffer);
}
}
class PersonClientHandler extends SimpleChannelHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
Person person = new Person("杨少飞", 24, 8888.88);
System.out.println("Send Message: " + person);
e.getChannel().write(person);
}
//接収Server的反馈
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
System.out.println("Server response Message: "+e.getMessage());
}
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
System.out.println("Unexpected exception from downstream."
+ e.getCause());
e.getChannel().close();
}
}
public class NettyClient {
public void testClient() {
// 创建客户端channel的辅助类,发起connection请求
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline pipeline = Channels.pipeline();
// pipeline.addLast("decoder", new PersonClientDecoder());
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new PersonClientEncoder());
pipeline.addLast("handler", new PersonClientHandler());
return pipeline;
}
});
ChannelFuture future = bootstrap.connect(new InetSocketAddress(
"localhost", 3333));
System.out.println("Client is on ....");
future.getChannel().getCloseFuture().awaitUninterruptibly();
bootstrap.releaseExternalResources();
}
}
PersonTest.java
package yang.netty.test;
public class PersonTest {
public static void main(String[] args) {
NettyServer server = new NettyServer();
NettyClient client = new NettyClient();
server.testServer();
client.testClient();
}
}
运行结果
Server is on ....
Client is on ....
Send Message: Persons [name=杨少飞, age=24, salary=8888.88]
Recevied Message: Persons [name=杨少飞, age=24, salary=8888.88]
Server response Message: OK