【问题标题】:Ruby TCPSocket read until custom terminator characterRuby TCPSocket 读取直到自定义终止符
【发布时间】:2014-06-04 06:53:47
【问题描述】:

这是我监听客户端 TCP 套接字的代码:

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

我不喜欢的是逐字节字符串连接。它不应该是内存效率的。

socket 的read 方法读取到换行为止。套接字是否可以读取到某个自定义终止符,例如 0x00

如果不是,那么你知道哪个内存效率高的字符串?

【问题讨论】:

    标签: ruby sockets string-concatenation terminator


    【解决方案1】:

    您可以将IO#gets 与自定义分隔符一起使用:

    # 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
    

    使用Netcat测试服务器:

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

    输出:

    $ ruby tcp_test.rb
    foo
    

    您甚至可以将输入记录分隔符设置为"\0"

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

    【讨论】:

    • 请解释$/ = "\0"
    • $/global variablegetschomp 和其他人使用的默认输入记录分隔符。它的默认值为"\n"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多