Skip to content

Instantly share code, notes, and snippets.

@rderoldan1
Created July 23, 2012 19:33
Show Gist options
  • Save rderoldan1/3165693 to your computer and use it in GitHub Desktop.
Save rderoldan1/3165693 to your computer and use it in GitHub Desktop.
simple example of ruby sockets

How to run

  1. first run the server

     ruby simple_server.rb
    
  2. then run the client

     ruby simple_client.rb
    
require 'socket' # Sockets are in standard library
hostname = 'localhost'
port = 2000
s = TCPSocket.open(host, port)
while line = s.gets # Read lines from the socket
puts line.chop # And print with platform line terminator
end
s.close # Close the socket when done
require 'socket' # Get sockets from stdlib
server = TCPServer.open(2000) # Socket to listen on port 2000
loop { # Servers run forever
client = server.accept # Wait for a client to connect
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment