Skip to content

Instantly share code, notes, and snippets.

@dergachev
Created November 8, 2013 20:06
Show Gist options
  • Save dergachev/7376861 to your computer and use it in GitHub Desktop.
Save dergachev/7376861 to your computer and use it in GitHub Desktop.
Proof of concept of ruby socket programming.
#!/usr/bin/ruby
require 'socket'
port = 2008
puts "Starting up server. You can connect by running 'nc localhost #{port}'."
server = TCPServer.new(port)
while (session = server.accept)
## Here we will establish a new thread for a connection client
Thread.start do
## I want to be sure to output something on the server side
## to show that there has been a connection
puts "Connection from #{session.peeraddr[2]} at #{session.peeraddr[3]}"
## lets see what the client has to say by grabbing the input
## then display it. Please note that the session.gets will look
## for an end of line character "\n" before moving forward.
input = session.gets
puts "client: #{input}"
# respond with a welcome message
session.puts "Server: Welcome #{session.peeraddr[2]}\n"
# falling out of the Thread block terminates the session
puts "Sending goodbye"
session.puts "Server: Goodbye\n"
end
end
__END__
See resources:
http://www.tutorialspoint.com/ruby/ruby_socket_programming.htm
https://www6.software.ibm.com/developerworks/education/l-rubysocks/l-rubysocks-a4.pdf
https://github.com/eventmachine/eventmachine/wiki/Code-Snippets
https://gist.github.com/sandro/1192557
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment