tags:

views:

51

answers:

1

I want to write a simple server socket in Ruby, which, when a client connects to it, prints a message and closes the client connection. I came up with:

require 'socket'

server = TCPServer.open('localhost',8800) 

loop {            
    client = server.accept
    Thread.start do
      s = client
      s.puts "Closing the connection. Bye!"
      s.close
    end         
}

However, when I access "localhost:8800" in my browser, I am not getting that message, instead, it says page not found.. What am I doing wrong here?

+3  A: 

It is quite likely that your browser is expecting something on the remote end that talks Http.

This is dependant upon your browser and also the exact URI you typed in. It is also possible that your browser is connecting getting the connection close and then displaying an error page.

If you want to see the server working then use telnet from a command prompt. So in one window type ruby ./myfilename.rb and then in another type telnet localhost 8800

Steve Weet
Correct. The first thing the browser will do after opening the connection is do a GET request for the document specified in the URL, which most likely was an implied '/index.html'. Since the server didn't send it and didn't send the proper responses the browser gave up. Browsers know about HTTP, which is a defined series of commands. A raw socket connection sits at the other end of the IP spectrum and could be any protocol. The programmer has to write all the intervening smarts into the socket server to make it all work.
Greg