Created
January 17, 2011 12:27
-
-
Save ecylmz/782794 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
require 'socket' | |
host,port = ARGV | |
begin | |
STDOUT.print "Connecting..." | |
STDOUT.flush | |
s = TCPSocket.open(host,port) | |
STDOUT.puts "done" | |
local,peer =s.addr,s.peeraddr | |
STDOUT.print "Connected to #{peer[2]}:#{peer[1]}" | |
STDOUT.puts " using local port #{local[1]}" | |
begin | |
sleep(0.5) | |
msg =s.read_nonblock(4096) | |
STDOUT.puts msg.chop | |
rescue SystemCallError | |
end | |
loop do | |
STDOUT.print '> ' | |
STDOUT.flush | |
local = STDIN.gets | |
break if !local | |
s.puts(local) | |
s.flush | |
response = s.readpartial(4096) | |
puts(response.chop) | |
end | |
rescue | |
puts $! | |
ensure | |
s.close if s | |
end |
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
require 'socket' | |
server = TCPServer.open(2000) # Listen on port 2000 | |
sockets = [server] # An array of sockets we'll monitor | |
log = STDOUT # Send log messages to standard out | |
while true # Servers loop forever | |
ready = select(sockets) # Wait for a socket to be ready | |
readable = ready[0] # These sockets are readable | |
readable.each do |socket| # Loop through readable sockets | |
if socket == server # If the server socket is ready | |
client = server.accept # Accept a new client | |
sockets << client # Add it to the set of sockets | |
# Tell the client what and where it has connected. | |
client.puts "Reversal service v0.01 running on #{Socket.gethostname}" | |
# And log the fact that the client connected | |
log.puts "Accepted connection from #{client.peeraddr[2]}" | |
else # Otherwise, a client is ready | |
input = socket.gets # Read input from the client | |
# If no input, the client has disconnected | |
if !input | |
log.puts "Client on #{socket.peeraddr[2]} disconnected." | |
sockets.delete(socket) # Stop monitoring this socket | |
socket.close # Close it | |
next # And go on to the next | |
end | |
if (input == "quit") # If the client asks to quit | |
socket.puts("Bye!"); # Say goodbye | |
log.puts "Closing connection to #{socket.peeraddr[2]}" | |
sockets.delete(socket) # Stop monitoring the socket | |
socket.close # Terminate the session | |
else # Otherwise, client is not quitting | |
socket.puts(input) # So reverse input and send it back | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment