Netty Client

This commit is contained in:
lyr90329 2014-07-31 14:59:30 +08:00
parent 4026bba33b
commit 44cf4e28f0
2 changed files with 60 additions and 0 deletions

39
src/client/Client.java Normal file
View File

@ -0,0 +1,39 @@
package 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.socket.nio.NioClientSocketChannelFactory;
public class Client
{
ClientBootstrap bootstrap;
ChannelFuture channelFuture;
String host;
int port;
int id;
public boolean init(String host, int port)
{
bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(new MClientPipelineFactory());
// Start the connection attempt.
channelFuture = bootstrap.connect(new InetSocketAddress(host, port));
return channelFuture.isSuccess();
}
public void stop()
{
channelFuture.awaitUninterruptibly();
if (!channelFuture.isSuccess())
{
channelFuture.getCause().printStackTrace();
}
channelFuture.getChannel().getCloseFuture().awaitUninterruptibly();
bootstrap.releaseExternalResources();
}
}

View File

@ -0,0 +1,21 @@
package client;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import server.MDecoder;
import server.MEncoder;
public class MClientPipelineFactory implements ChannelPipelineFactory
{
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new MDecoder());
pipeline.addLast("encoder", new MEncoder());
return pipeline;
}
}