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:
# 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.