From: Tomoyuki Kosimizu Date: 2000-02-15T07:46:10+09:00 Subject: [ruby-talk:01345] thread specific data in Ruby Hi, I wanted another version of IO#gets which limits line length read. Although this is not good example, I should be happy to be of any help to you. BUFSIZ = 8192 def read_char(io) str = result = nil if not Thread.current[:_read_char_count] or Thread.current[:_read_char_count] == 0 begin str = io.sysread(BUFSIZ) rescue Errno::EINTR retry rescue EOFError if str.nil? or str.size == 0 Thread.current[:_read_char_buff] = nil Thread.current[:_read_char_count] = 0 return -1 end end Thread.current[:_read_char_buff] = str Thread.current[:_read_char_count] = str.size end result = Thread.current[:_read_char_buff][Thread.current[:_read_char_buff].size - Thread.current[:_read_char_count]] Thread.current[:_read_char_count] -= 1 result end def read_line(io, maxlen) line = '' for i in 1..maxlen c = read_char(io) if c < 0 if line.size == 0 return nil else break end end line << c.chr if c == ?\n break end end if i == maxlen and line[-1] != ?\n raise 'too long line' end line end require 'socket' accepter = TCPServer.open(0) print('server is on ', (accepter.addr)[1], $/) loop do conn = accepter.accept print(conn, ' is accepted', $/) Thread.start { soc = conn while (line = read_line(soc, 1024)) line.chomp! soc.write(line << "\r\n") end print(soc, ' is gone', $/) soc.close } end # tomoyuki kosimizu # greentea@fa2.so-net.ne.jp