Socket level network programming

I'm trying to learn a bit about socket level programming (using ruby, of
course); I'm running into what I'm sure is a simple problem but I'm
stuck.

Here's the code:

#server
require 'socket'

server = TCPServer.new('127.0.0.1', 12345)
while (session = server.accept)
  puts "Request length: #{session.gets.length}"
  $stdout.flush
  session.close
end

···

-------------------------------------------------

#client
require 'socket'

l = 1000
sock = TCPSocket.new('127.0.0.1', 12345)
packet = "1" * l
sock.send(packet, 0)
sock.close

-------------------------------------------------

Up to a certain length, everything works fine, but over that the server
crashes with a

server.rb:5:in `gets': Invalid argument (Errno::EINVAL)

What's the right way to handle this?

martin