title: Trying to create a simple Ruby server over SSL
body: <p>I am trying to create a simple SSL client and server in Ruby.  But I'm getting a cryptic error message and the documentation is of no help.</p>
  
  <p>Here is my server code:</p>
  
  <pre><code>#!/usr/bin/ruby
  
  require "gserver"
  require "openssl"
  
  listeningPort = Integer(ARGV[0])
  
  class Server &lt; GServer
    def initialize(listeningPort)
      @sslContext = OpenSSL::SSL::SSLContext.new
      @sslContext.cert = OpenSSL::X509::Certificate.new(File.open("MyCert.pem"))
      super(listeningPort, "0.0.0.0")
    end
    def serve(io)
      begin
        ssl = OpenSSL::SSL::SSLSocket.new(io, @sslContext)
        ssl.sync_close = true
        ssl.connect
        while (lineIn = ssl.gets)
          lineIn = lineIn.chomp
          $stdout.puts "=&gt; " + lineIn
          lineOut = "You said: " + lineIn
          $stdout.puts "&lt;= " + lineOut
          ssl.puts lineOut
        end
      rescue
        $stderr.puts $!
      end
    end
  end
  
  server = Server.new(listeningPort)
  server.start
  server.join
  </code></pre>
  
  <p>The client code is similar:</p>
  
  <pre><code>#!/usr/bin/ruby
  
  require "socket"
  require "thread"
  require "openssl"
  
  host = ARGV[0]
  port = Integer(ARGV[1])
  
  socket = TCPSocket.new(host, port)
  sslContext = OpenSSL::SSL::SSLContext.new
  sslContext.cert = OpenSSL::X509::Certificate.new(File.open("MyCert.pem"))
  ssl = OpenSSL::SSL::SSLSocket.new(socket, sslContext)
  ssl.sync_close = true
  ssl.connect
  puts ssl.peer_cert   # this is nil
  
  Thread.new {
    begin
      while lineIn = ssl.gets
        lineIn = lineIn.chomp
        $stdout.puts lineIn
      end
    rescue
      $stderr.puts "Error in input loop: " + $!
    end
  }
  
  while (lineOut = $stdin.gets)
    lineOut = lineOut.chomp
    ssl.puts lineOut
  end
  </code></pre>
  
  <p>When I connect, I get this error on both the server and the client:</p>
  
  <pre><code>in `connect': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol (OpenSSL::SSL::SSLError)
  </code></pre>
  
  <p>The problem could be that it doesn't trust the certificate (self-signed).  I'm not sure how to tell the client to trust that certificate.  Above, I have put the server's cert in the context, but that was just a shot in the dark.  I'm not even sure my certificate is in an acceptable format (it is in base64 with the cert and the private key in the file).  The documentation is very scant and there doesn't seem to be much on the web in this area either. </p>
  
  <p>Any ideas?</p>