Files
space_game_server/lib/app.rb
T

61 lines
1.7 KiB
Ruby

# Nathan Hinton 22 Dec 2025
# Here is where I will have the server start
require 'socket'
require 'json'
require 'yaml'
require 'game/game'
server = TCPServer.new(2000)
puts "Multithreaded server listening on port 2000..."
conf_data = {}
configuration_file = 'game_data/game_conf.yaml'
File.open(configuration_file, 'r') do |fi|
conf_data = YAML.safe_load(fi.read())
end
puts "loaded #{conf_data} for game"
game = Game::Game.new(conf_data)
game_thread = Thread.new() do
game.run()
end
loop do
# Accept the connection and pass the client object to a new thread
Thread.start(server.accept) do |client|
puts "New thread started for a client connection."
# Now we start to connect commands to the server
#client.puts ({'type' => 'update', 'domain' => 'game', 'request_id' => nil, 'payload' => {'game_name' => conf_data['name']}}).to_json
# Read data from the client
while line = client.gets
# Ensure that it is JSON
begin
encoded_command = JSON.parse(line.chomp)
response = ''
if encoded_command['type'] == 'hello'
# Here we need to get the client information.
response = game.player_connect(client, encoded_command).to_json
else
response = game.parse_command(encoded_command).to_json
end
puts "Received: #{line.chomp}"
puts "Sending: #{response}"
client.puts "#{response}"
rescue JSON::ParserError
puts "Error decoding JSON: '#{line.chomp}'"
client.puts ({'type' => 'error', 'domain' => 'error', 'payload' => 'Server unable to decode JSON'}).to_json()
end
end
client.close
puts "Thread completed and client disconnected."
end
end