-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_server.rb
67 lines (54 loc) · 1.63 KB
/
file_server.rb
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'socket'
require 'logger'
require 'webrick'
include Socket::Constants
class FileServer
attr_accessor :song
def initialize
@socket = Socket.new(AF_INET, SOCK_STREAM, 0)
@socket.bind(Socket.sockaddr_in(62580, '0.0.0.0'))
@logger = Logger.new(STDOUT)
@logger.level = Logger::INFO
@song = 'mp3/default.mp3'
end
def start_listening
@socket.listen(5)
loop do
begin
# Listening on socket
client_socket, client_addrinfo = @socket.accept_nonblock
@logger.info('[Fileserver] A client asked for the song')
# Parse HTTP request
room = get_room_id client_socket.gets
room = RoomManager.instance.get_room_by_id room.to_i
@logger.info 'test'
@logger.info room.song[:file]
# Send the song in a new process as ruby has a Global Interpreter Lock which may lock the whole server
Process.fork {
begin
unless room.nil?
http_string = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Type: audio/mpeg\r\n\r\n" + File.read(room.song[:file])
client_socket.write http_string
client_socket.close
end
exit(0)
rescue Errno::EPIPE
client_socket.close
exit(0)
end
}
rescue IO::WaitReadable, Errno::EINTR
IO.select([@socket])
retry
end
end
end
def get_room_id(request_line)
request_uri = request_line.split(" ")[1]
path = URI.unescape(URI(request_uri).path)
clean = []
# Split the path into components
parts = path.split("/")
parts[1]
end
end