Ruby TCPSocket read until custom terminator character

2.6k Views Asked by At

Here is my code to listen client TCP socket:

def initialize
    @msg = ''
    @messages = Queue.new
    @socket = TCPSocket.open('127.0.0.1', 2000)
    Thread.new do
        loop do
            ch = @socket.recv(1)
            if ch == "\n"
                puts @msg unless @msg.blank?
                @msg = ''
            else
                @msg += ch
            end
        end
    end
end

What I don't like is byte-by-byte string concatenation. It should be not memory-efficient.

The read method of socket reads until newline. Could the socket read until some custom terminator character, for example 0x00 ?

If not, then which memory-efficient string appenging do you know?

1

There are 1 best solutions below

2
On BEST ANSWER

You could use IO#gets with a custom separator:

# tcp_test.rb
require 'socket'

TCPSocket.open('127.0.0.1', 2000) do |socket|
  puts socket.gets("\0").chomp("\0") # chomp removes the separator
end

Test server using Netcat:

$ echo -ne "foo\0bar" | nc -l 2000

Output:

$ ruby tcp_test.rb
foo

You could even set the input record separator to "\0":

$/ = "\0"
puts socket.gets.chomp