- require 'socket'
- server = TCPServer.open(2000) # Listen on port 2000
- sockets = [server] # An array of sockets we'll monitor
- log = STDOUT # Send log messages to standard out
- while true # Servers loop forever
- ready = select(sockets) # Wait for a socket to be ready
- readable = ready[0] # These sockets are readable
- readable.each do |socket| # Loop through readable sockets
- if socket == server # If the server socket is ready
- client = server.accept # Accept a new client
- sockets << client # Add it to the set of sockets
- # Tell the client what and where it has connected.
- client.puts "Reversal service v0.01 running on #{Socket.gethostname}"
- # And log the fact that the client connected
- log.puts "Accepted connection from #{client.peeraddr[2]}"
- else # Otherwise, a client is ready
- input = socket.gets # Read input from the client
- # If no input, the client has disconnected
- if !input
- log.puts "Client on #{socket.peeraddr[2]} disconnected."
- sockets.delete(socket) # Stop monitoring this socket
- socket.close # Close it
- next # And go on to the next
- end
- input.chop! # Trim client's input
- if (input == "quit") # If the client asks to quit
- socket.puts("Bye!"); # Say goodbye
- log.puts "Closing connection to #{socket.peeraddr[2]}"
- sockets.delete(socket) # Stop monitoring the socket
- socket.close # Terminate the session
- else # Otherwise, client is not quitting
- socket.puts(input.reverse) # So reverse input and send it back
- end
- end
- end
- end
- #该片段来自于http://www.codesnippet.cn/detail/090420132772.html
来源: http://www.codesnippet.cn/detail/090420132772.html