C Socket Code in Ruby
When designing socket code to be implemented in C, it may well make sense to first sketch out the design in Ruby. The Socket
class provides thin wrappings for just about all of the relevant C standard library functions. There also is the fcntl
module, and select
in Kernel
. The socket code can thus be just about the same in Ruby as it would be in C, but trying out different designs for say managing sessions in a server is much less tedious in Ruby.
@ssock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, Socket::IPPROTO_TCP) sockaddr = Socket.pack_sockaddr_in(@port, 'localhost') @ssock.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true) @ssock.bind(sockaddr)