Skip to content

Instantly share code, notes, and snippets.

@colszowka
Created December 1, 2012 09:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colszowka/4181353 to your computer and use it in GitHub Desktop.
Save colszowka/4181353 to your computer and use it in GitHub Desktop.
# 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
# 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
# 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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment