public
Last active

  • Download Gist
1-ruby_socket.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Blocks while a client is connected, and does not time out automatically
require 'socket'
require 'etc'
 
Socket.unix_server_loop("/tmp/sock") do |socket|
begin
login = Etc.getpwuid(socket.getpeereid.first).name
puts "#{login} connected"
input = socket.gets.strip
puts "#{login} sent #{input}"
socket.puts 'OK'
ensure
socket.close
end
end
2-em_socket.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# Cannot access connecting clients UID in event machine socket :(
require 'eventmachine'
 
module Handler
def post_init
log "Got connection!"
@login = '' # How can I get the connected UID?
end
 
def receive_data data
@data_received ||= ""
@data_received << data
if @data_received.include?("\n")
puts "#{@login} #{@data_received.split("\n").first}"
send_data 'OK' and close_connection_after_writing
end
end
end
 
EventMachine.run do
socket_path = '/tmp/sock'
EventMachine.start_server socket_path, Handler
puts "Now accepting connections at #{socket_path}"
end
3-cell_socket.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# Celluloid example. Multiple connections work without problems, but the actors do not terminate properly and I need a kill -9
 
require 'socket'
require 'etc'
require 'Celluloid'
 
class Connection
include Celluloid
attr_reader :socket
def initialize(socket)
@socket = socket
@login = Etc.getpwuid(socket.getpeereid.first).name
end
 
def listen
input = socket.gets.strip
puts "#{@login} : #{input}"
socket.puts "OK"
ensure
socket.close
Actor.current.terminate
end
end
 
 
Socket.unix_server_loop("/tmp/sock") do |socket|
puts 'got connection'
Connection.new(socket).async.listen
puts "listening (again)"
end
4-ruby_socket-with_timeout.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
require 'socket'
require 'etc'
require 'timeout'
 
# Using timeout class as suggested by @bjhaid on SO.
# Will block while connected, but processes further requests after previous time out or send.
# Blocking could be remedied by forking or threading the processing code manually.
Socket.unix_server_loop("/tmp/sock") do |socket|
begin
login = Etc.getpwuid(socket.getpeereid.first).name
puts "#{login} connected"
 
Timeout.timeout 3 do
input = socket.gets.strip
puts "#{login}: #{input}"
socket.puts "OK"
end
rescue Timeout::Error
puts "Timeout"
socket.puts "TIMEOUT"
ensure
socket.close
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.