Created
October 28, 2015 21:01
-
-
Save hayduke19us/670172bfec91f34e50ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "socket" | |
| require "json" | |
| require "colorize" | |
| require 'securerandom' | |
| # require "./lib/models/weather" | |
| # this is where it was connecting and not disconnecting | |
| ## ===> Sequel.connect(database_urls.last) | |
| class Server | |
| DB = Sequel.connect(database_urls.last) | |
| attr_reader :connections, :server | |
| def initialize(ip, port) | |
| @server = TCPServer.open ip, port | |
| @connections = Hash.new | |
| @clients = Hash.new | |
| @connections[:server] = @server | |
| @connections[:clients] = @clients | |
| end | |
| def run | |
| loop { | |
| Thread.start(self.server.accept) do | client | | |
| client_id = SecureRandom.uuid | |
| puts "#{client_id}: #{client}" | |
| self.connections[:clients][client_id] = client | |
| self.poll_weather client | |
| end | |
| } | |
| end | |
| def poll_weather client | |
| # 'old' needs to stay out side of the loop and is reset each time regardless. | |
| old = Weather.current | |
| loop { | |
| current = Weather.current | |
| state = weather_diff?(old, current) ? 1 : 0 | |
| send_global_msg 'New Weather' if state > 0 | |
| old = current | |
| } | |
| end | |
| def weather_diff? old, current | |
| old[:id] != current[:id] | |
| end | |
| def message client, state | |
| client.puts state if state > 0 | |
| end | |
| def connections? | |
| self.connections[:clients].count > 1 | |
| end | |
| def send_global_msg msg | |
| self.connections[:clients].each do |id, connection| | |
| connection.puts msg | |
| end | |
| end | |
| end | |
| # (ip, port) in each machine "localhost" = 127.0.0.1 | |
| desc "Start a socket server" | |
| namespace :socket do | |
| task :start do | |
| server = Server.new("localhost", 3000) | |
| server.run | |
| DB.disconnect | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment