Guest User

Untitled

a guest
Jul 21st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. package ca.grimoire.caprox;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetSocketAddress;
  5. import java.nio.ByteBuffer;
  6.  
  7. import org.jboss.xnio.ChannelListener;
  8. import org.jboss.xnio.IoUtils;
  9. import org.jboss.xnio.OptionMap;
  10. import org.jboss.xnio.TcpConnector;
  11. import org.jboss.xnio.TcpServer;
  12. import org.jboss.xnio.Xnio;
  13. import org.jboss.xnio.channels.Channels;
  14. import org.jboss.xnio.channels.TcpChannel;
  15.  
  16. public final class SimpleForwardServer {
  17.  
  18. private static final class ForwardListener implements
  19. ChannelListener<TcpChannel> {
  20. public ForwardListener(TcpChannel destination) {
  21. this.destination = destination;
  22. }
  23.  
  24. private final TcpChannel destination;
  25.  
  26. public void handleEvent(final TcpChannel channel) {
  27. final ByteBuffer buffer = ByteBuffer.allocate(512);
  28. int res;
  29. try {
  30. while ((res = channel.read(buffer)) > 0) {
  31. buffer.flip();
  32. Channels.writeBlocking(destination, buffer);
  33. }
  34. // make sure everything is flushed out
  35. Channels.flushBlocking(channel);
  36. if (res == -1) {
  37. channel.close();
  38. } else {
  39. channel.resumeReads();
  40. }
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. IoUtils.safeClose(channel);
  44. }
  45. }
  46. }
  47.  
  48. public static void main(String[] args) throws Exception {
  49. final Xnio xnio = Xnio.create();
  50.  
  51. // Create an open listener.
  52. final TcpConnector connector = xnio.createTcpConnector(OptionMap.EMPTY);
  53.  
  54. final ChannelListener<TcpChannel> openListener = new ChannelListener<TcpChannel>() {
  55. public void handleEvent(final TcpChannel clientChannel) {
  56. final ChannelListener<TcpChannel> connectionCompletedListener = new ChannelListener<TcpChannel>() {
  57. @Override
  58. public void handleEvent(TcpChannel serverChannel) {
  59. serverChannel.getReadSetter().set(
  60. new ForwardListener(clientChannel));
  61. serverChannel.resumeReads();
  62.  
  63. clientChannel.getReadSetter().set(
  64. new ForwardListener(serverChannel));
  65. clientChannel.resumeReads();
  66. }
  67. };
  68.  
  69. InetSocketAddress dest = new InetSocketAddress("localhost",
  70. 5672);
  71. connector.connectTo(dest, connectionCompletedListener, null);
  72. }
  73. };
  74.  
  75. // Create the server.
  76. final TcpServer server = xnio.createTcpServer(openListener,
  77. OptionMap.EMPTY);
  78.  
  79. // Bind it.
  80. server.bind(new InetSocketAddress(12345));
  81. }
  82. }
Add Comment
Please, Sign In to add comment