Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ca.grimoire.caprox;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.ByteBuffer;
- import org.jboss.xnio.ChannelListener;
- import org.jboss.xnio.IoUtils;
- import org.jboss.xnio.OptionMap;
- import org.jboss.xnio.TcpConnector;
- import org.jboss.xnio.TcpServer;
- import org.jboss.xnio.Xnio;
- import org.jboss.xnio.channels.Channels;
- import org.jboss.xnio.channels.TcpChannel;
- public final class SimpleForwardServer {
- private static final class ForwardListener implements
- ChannelListener<TcpChannel> {
- public ForwardListener(TcpChannel destination) {
- this.destination = destination;
- }
- private final TcpChannel destination;
- public void handleEvent(final TcpChannel channel) {
- final ByteBuffer buffer = ByteBuffer.allocate(512);
- int res;
- try {
- while ((res = channel.read(buffer)) > 0) {
- buffer.flip();
- Channels.writeBlocking(destination, buffer);
- }
- // make sure everything is flushed out
- Channels.flushBlocking(channel);
- if (res == -1) {
- channel.close();
- } else {
- channel.resumeReads();
- }
- } catch (IOException e) {
- e.printStackTrace();
- IoUtils.safeClose(channel);
- }
- }
- }
- public static void main(String[] args) throws Exception {
- final Xnio xnio = Xnio.create();
- // Create an open listener.
- final TcpConnector connector = xnio.createTcpConnector(OptionMap.EMPTY);
- final ChannelListener<TcpChannel> openListener = new ChannelListener<TcpChannel>() {
- public void handleEvent(final TcpChannel clientChannel) {
- final ChannelListener<TcpChannel> connectionCompletedListener = new ChannelListener<TcpChannel>() {
- @Override
- public void handleEvent(TcpChannel serverChannel) {
- serverChannel.getReadSetter().set(
- new ForwardListener(clientChannel));
- serverChannel.resumeReads();
- clientChannel.getReadSetter().set(
- new ForwardListener(serverChannel));
- clientChannel.resumeReads();
- }
- };
- InetSocketAddress dest = new InetSocketAddress("localhost",
- 5672);
- connector.connectTo(dest, connectionCompletedListener, null);
- }
- };
- // Create the server.
- final TcpServer server = xnio.createTcpServer(openListener,
- OptionMap.EMPTY);
- // Bind it.
- server.bind(new InetSocketAddress(12345));
- }
- }
Add Comment
Please, Sign In to add comment