Ruby Socket Programming

Socket programming is a method of communication between two computers using a network protocol, typically TCP/IP. In Ruby, the socket standard library provides the capabilities to create both server and client sockets for communication.

Here's a basic tutorial on socket programming in Ruby.

1. Basic TCP Server

require 'socket'

server = TCPServer.new(8080)

loop do
  socket = server.accept
  request = socket.gets
  STDERR.puts request

  response = "Hello World!\n"

  socket.print "HTTP/1.1 200 OK\r\n" +
               "Content-Type: text/plain\r\n" +
               "Content-Length: #{response.bytesize}\r\n" +
               "Connection: close\r\n"

  socket.print "\r\n"

  socket.print response
  socket.close
end

In this example, we're creating a basic HTTP server that listens on port 8080 and responds with "Hello World!" to any request.

2. Basic TCP Client

require 'socket'

socket = TCPSocket.new('localhost', 8080)
socket.print "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"
response = socket.read

headers, body = response.split("\r\n\r\n", 2)

print body

This client connects to the server we created above, sends a basic HTTP GET request, and then prints out the response body.

Some Notes

  • When we call TCPServer.new(8080), it binds a new TCP server to port 8080. The server will listen on this port for incoming connections.
  • The server.accept call is blocking, meaning it will wait until a client connects to the server. When a client connects, it returns a TCPSocket object that we can read from and write to.
  • The socket.gets call reads one line from the socket. In this case, it's reading the first line of the HTTP request.
  • We then create an HTTP response and write it to the socket with socket.print.
  • Finally, we close the socket. If we didn't do this, the client would continue waiting for a response.

This is a very basic introduction to socket programming in Ruby. There's much more you can do, including handling multiple clients at the same time, using non-blocking I/O, and more. However, this should give you a good starting point.

  1. Creating sockets in Ruby: Use the Socket class to create sockets.

    require 'socket'
    
    server_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
    
  2. TCP socket programming in Ruby: Create a TCP server and client for communication.

    # TCP Server
    server = TCPServer.new(2000)
    
    # TCP Client
    client = TCPSocket.new('localhost', 2000)
    
  3. UDP socket programming in Ruby: Use UDP for connectionless communication.

    # UDP Server
    server = UDPSocket.new
    
    # UDP Client
    client = UDPSocket.new
    
  4. Socket communication in Ruby: Send and receive data over sockets.

    # Server
    client_socket = server.accept
    data = client_socket.recv(1024)
    
    # Client
    client.send('Hello, server!', 0, server_addr, server_port)
    
  5. Ruby socket server example: Implement a basic TCP server.

    require 'socket'
    
    server = TCPServer.new(2000)
    
    loop do
      client = server.accept
      client.puts 'Hello, client!'
      client.close
    end
    
  6. Ruby socket client example: Implement a basic TCP client.

    require 'socket'
    
    client = TCPSocket.new('localhost', 2000)
    puts client.gets
    client.close
    
  7. Handling multiple connections in Ruby sockets: Use threads or event-driven frameworks to handle multiple connections.

    # Using threads
    loop do
      Thread.start(server.accept) do |client|
        client.puts 'Hello, client!'
        client.close
      end
    end
    
  8. Socket options and configurations in Ruby: Configure socket options for specific behaviors.

    server.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
    
  9. Securing socket connections in Ruby: Use SSL/TLS for secure socket communication.

    require 'openssl'
    
    context = OpenSSL::SSL::SSLContext.new
    context.cert = OpenSSL::X509::Certificate.new(File.open('server.crt'))
    context.key = OpenSSL::PKey::RSA.new(File.open('server.key'))
    ssl_server = OpenSSL::SSL::SSLServer.new(server, context)
    
  10. Non-blocking socket programming in Ruby: Implement non-blocking I/O with IO.select or event-driven frameworks.

    # Using IO.select
    read, _, _ = IO.select([server])
    client = read[0].accept
    
  11. Ruby socket timeouts and retries: Set timeouts for socket operations and implement retry mechanisms.

    require 'timeout'
    
    begin
      Timeout.timeout(5) do
        client_socket.recv(1024)
      end
    rescue Timeout::Error
      puts 'Operation timed out'
    end
    
  12. Broadcasting with sockets in Ruby: Broadcast data to multiple recipients.

    # UDP Broadcast Server
    server.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
    
    # UDP Broadcast Client
    client.send('Broadcast message', 0, '255.255.255.255', server_port)
    
  13. Socket programming for inter-process communication in Ruby: Use UNIX domain sockets or other IPC mechanisms for communication between processes.

    # UNIX Domain Socket
    server = UNIXServer.new('/tmp/socket.sock')
    client = UNIXSocket.new('/tmp/socket.sock')