Sockets programming in RubyExplore Ruby's fundamental sockets interfaces for networkingapplicationsSkill Level: IntermediateM. Tim Jones (mtj@mtjones.com)Senior Principal Software EngineerEmulex Corp.
I am pulling out text and putting it here that is relevant to me for later use. Basically this post is my note taking system...You can create a stream server socket using the TCPServer class. To this method, you provide the address to which you'll bind the port. In most cases, you bind to the INADDR_ANY ("0.0.0.0"), which lets you accept connections from any of the available interfaces on the host. This can be done in the following ways (binding to port 23000):Listing 5. Creating a stream server socket (theses two are the same)
servSock = TCPServer::new( "0.0.0.0", 23000 )
servSock = TCPServer::new( "", 23000 )
Note that the bind and listen are done for you as part of the TCPServer socketcreation.Listing 6. Closing a socket
servSock::close
Once the server socket is established it is possible to create a new socket upon incoming connections.newsock = servSock.accept
Now you can read and write to the new socket.msg = newsock.read
newsock.write("You are connected.\n")
Here is the script I modified from the above document:require 'socket'class Connection def initialize( port ) @descriptors = Array::new @serverSocket = TCPServer.new( "", port ) @serverSocket.setsockopt( Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1 ) printf("Now listening on port %d\n", port) @descriptors.push( @serverSocket ) end def run while 1 res = select( @descriptors, nil, nil, nil ) if res != nil then # Iterate through the tagged read descriptors for sock in res[0] # Received a connect to the server (listening) socket if sock == @serverSocket then puts "Accepting new connection. \n" accept_new_connection else # Received something on a client socket if sock.eof? then str = sprintf("Client left %s:%s\n", sock.peeraddr[2], sock.peeraddr[1]) printf(str) #broadcast_string( str, sock ) sock.close @descriptors.delete(sock) else str = sprintf("[%s|%s]: %s\n", sock.peeraddr[2], sock.peeraddr[1], sock.gets() ) #broadcast_string( str, sock ) printf(str) end end end end end end def end_connection @serverSocket.close @descriptors = [] end private def accept_new_connection newsock = @serverSocket.accept_nonblock @descriptors.push( newsock ) #newsock.write("You're connected to the Ruby chatserver\n") str = sprintf("Client joined %s:%s\n", newsock.peeraddr[2], newsock.peeraddr[1]) printf(str) #broadcast_string( str, newsock ) end def broadcast_string( string, omit_sock ) @descriptors.each do |clisock| if clisock != @serverSocket && clisock != omit_sock clisock.write(string) end end print(string) endend