Search code examples
rubysocketsserverclienttcpsocket

Ruby TCPSocket communication


I am learning TCPSocket and have a simple server written:

require 'socket'

server = TCPServer.open(2000)

loop {
  client = server.accept
  p client.gets
  client.print("bar")
  client.close
}

and simple client written:

require 'socket'

hostname = 'localhost'
port = 2000
socket = TCPSocket.open(hostname, port)

socket.print("foo")
p socket.gets

When I run these in separate terminals with either the server or client communicating one way (i.e. one "prints" and the other "gets") I get the expected string on the other side. When I run these as written, with the client first "print"-ing a message to the server and then the server "gets"ing it to then "print" a string to the client, it just hangs. What is causing this issue?


Solution

  • Your program does following:

    The connection is established between client and server.

    Client side

    • Calls print("foo") - exactly 3 bytes are transmitted to the server.
    • Calls gets - waits for data from server but server never send any.

    Server side

    • Calls gets - The ruby function gets parse stream data and it always return the whole line. But the server received only "foo" and the it has no idea whether it is whole line or not. So it is waiting forever for new line character which client never send.