Created
November 22, 2009 01:23
-
-
Save bernerdschaefer/240365 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Naive proxy server to route data from 12345 to postgres as 5432 | |
// | |
// javac Server.java | |
// java -server Server | |
import java.io.IOException; | |
import java.nio.channels.*; | |
import java.nio.ByteBuffer; | |
import java.net.*; | |
public class Server { | |
private ServerSocketChannel server; | |
public Server() throws IOException { | |
this.server = ServerSocketChannel.open(); | |
this.server.socket().bind(new InetSocketAddress(12345)); | |
} | |
private void run() throws IOException { | |
for ( ;; ) { | |
SocketChannel socket = this.server.accept(); | |
socket.configureBlocking(false); | |
new Thread(new ProxyExecutor(socket)).start(); | |
} | |
} | |
public static void main(String[] args) { | |
try { | |
new Server().run(); | |
} | |
catch(IOException e) { | |
e.printStackTrace(); | |
System.exit(-1); | |
} | |
} | |
} | |
class ProxyExecutor implements Runnable { | |
private SocketChannel socket; | |
public ProxyExecutor(SocketChannel socket) { | |
this.socket = socket; | |
} | |
public void run() { | |
try { | |
SocketChannel postgres = SocketChannel.open(new InetSocketAddress(5432)); | |
postgres.configureBlocking(false); | |
ByteBuffer buffer = ByteBuffer.allocate(1024); | |
for ( ;; ) { | |
if ( this.socket.read(buffer) == -1 ) { | |
break; | |
} | |
buffer.flip(); | |
postgres.write(buffer); | |
buffer.clear(); | |
postgres.read(buffer); | |
buffer.flip(); | |
this.socket.write(buffer); | |
buffer.clear(); | |
} | |
postgres.close(); | |
this.socket.close(); | |
} | |
catch(Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Naive proxy to route data from 12345 to postgres on 5432 | |
# jruby --server server.rb | |
require 'socket' | |
server = TCPServer.new('0.0.0.0', 12345) | |
loop do | |
begin | |
socket = server.accept_nonblock | |
rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR | |
IO.select([server]) | |
retry | |
end | |
Thread.new do | |
begin | |
postgres = TCPSocket.new('0.0.0.0', 5432) | |
loop do | |
while (data = socket.read_nonblock(1024)) != "" | |
postgres.write data | |
end | |
while (data = postgres.read_nonblock(1024)) != "" | |
socket.write data | |
end | |
end | |
rescue EOFError | |
postgres.close | |
socket.close | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment