Recent comments


Syndicate


Follow Me

Twitter Facebook

Dumb server :)

I noticed that Ruby has a neat way in handling sockets, It makes it more natural and easy to read. But as usual, I can't be much satisfied without trying it myself... So I fired up the Ruby docs + a couple of googling. 

The idea was just to create a simple server that only accepts one client and they can throw messages to each other. In a typical chat, once two users are connected, any messages sent by whichever user will automatically be received by the other one and he can just continue to respond or just watch over until the buffer floods. 

I wanted the same functionality but somehow I didn't find anything which will emit a signal once a new message from the user has been received. I ended up having a server that waits for the user in the server to enter a message first then checks for response from the client, thats why I called it dumb server!

Here's the dumb source code:

require 'socket'

server = TCPServer.new("127.0.0.1", 2000)

puts "Server is now listening..."

client = server.accept
client.puts "Welcome Client!"

loop do
  print ">> "
  input = gets.chomp
  break if input == 'quit'
  client.puts input if !input.empty?
  incoming = client.gets.chomp
  puts ">> Client: #{incoming}" if !incoming.empty?
end

client.close

I know there's GServer which makes this even sweeter, I will probably use it when I need some serious piping but for this one I wanted to build something raw so I get my hands a bit dirty.

and here's how you use it:

Server

$ ruby server.rbServer is now listening...>> I have to go first>> Client: then Its my turn next>> quit
$

Client

$ telnet 127.0.0.1 2000
Trying 127.0.0.1...
Connected to 127.0.0.1 Escape character is '^]'.
Welcome Client!
I have to go first
then Its my turn next
Connection closed by foreign host.
$

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.