views:

24

answers:

1

I have a very simple Ruby program that acts as an "echo server". When you connect to it via telnet any text you type is echoed back. That part is working. If I add a 'putc' statement to also print each received character on the console running the program only the very first character displayed is printed. After that it continues to echo things back to the telnet client but there is nothing printed on the console.

The following is a small, stripped down program that exhibits the problem.

I am very new to Ruby and have probably made a typical rookie mistake. What did I do wrong?

require 'socket'  

puts "Simple Echo Server V1.0"  
server = TCPServer.new('127.0.0.1', '2150')  
cbuf = ""  

while socket = server.accept  
    cbuf = socket.readchar  
    socket.putc cbuf  
    putc cbuf  
end  
+1  A: 

The problem is that your code is only running the while loop once for every time somebody connects (TCPServer#accept accepts a connection). Try something more like:

require 'socket'  

puts "Simple Echo Server V1.0"  
server = TCPServer.new('127.0.0.1', '2150')

socket = server.accept  

while line = socket.readline
  socket.puts line
  puts line
end
joeldt
Thank you. Knew it would be something obvious I'd overlooked.
Timm