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?
You could use
IO#gets
with a custom separator:Test server using Netcat:
Output:
You could even set the input record separator to
"\0"
: