netty介绍:
Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
测试类
public abstract class ClientToServerTest extends TestCase {
protected static final String LOCALHOST = "127.0.0.1";
protected ExchangeServer server;
protected ExchangeChannel client;
protected WorldHandler handler = new WorldHandler();
protected abstract ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException;
protected abstract ExchangeChannel newClient(int port) throws RemotingException;
@Override
protected void setUp() throws Exception {
super.setUp();
int port = (int) (1000 * Math.random() + 10000);
server = newServer(port, handler);
client = newClient(port);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
try {
if (server != null)
server.close();
} finally {
if (client != null)
client.close();
}
}
@Test
public void testFuture() throws Exception {
ResponseFuture future = client.request(new World("world"));
Hello result = (Hello)future.get();
System.out.println(result.getName()+" hello world");
Assert.assertEquals("hello,world", result.getName());
}
}
Handle处理类
写道
public class WorldHandler implements Replier<World> {
public Class<World> interest() {
return World.class;
}
public Object reply(ExchangeChannel channel, World msg) throws RemotingException {
return new Hello("hello," + msg.getName());
}
}
public Class<World> interest() {
return World.class;
}
public Object reply(ExchangeChannel channel, World msg) throws RemotingException {
return new Hello("hello," + msg.getName());
}
}
NettyClientToServerTest类
写道
public class NettyClientToServerTest extends ClientToServerTest {
protected ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException {
return Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?server=netty"), receiver);
}
protected ExchangeChannel newClient(int port) throws RemotingException {
return Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?client=netty"));
}
}
protected ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException {
return Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?server=netty"), receiver);
}
protected ExchangeChannel newClient(int port) throws RemotingException {
return Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?client=netty"));
}
}