Class: Mjai::TCPGameServer

Inherits:
Object
  • Object
show all
Defined in:
lib/mjai/tcp_game_server.rb

Direct Known Subclasses

TCPActiveGameServer

Defined Under Namespace

Classes: LocalError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ TCPGameServer

Returns a new instance of TCPGameServer.



17
18
19
20
21
22
23
# File 'lib/mjai/tcp_game_server.rb', line 17

def initialize(params)
  @params = params
  @server = TCPServer.open(params[:host], params[:port])
  @players = []
  @mutex = Mutex.new()
  @num_finished_games = 0
end

Instance Attribute Details

#num_finished_gamesObject (readonly)

Returns the value of attribute num_finished_games.



25
26
27
# File 'lib/mjai/tcp_game_server.rb', line 25

def num_finished_games
  @num_finished_games
end

#paramsObject (readonly)

Returns the value of attribute params.



25
26
27
# File 'lib/mjai/tcp_game_server.rb', line 25

def params
  @params
end

#playersObject (readonly)

Returns the value of attribute players.



25
26
27
# File 'lib/mjai/tcp_game_server.rb', line 25

def players
  @players
end

Instance Method Details

#portObject



145
146
147
# File 'lib/mjai/tcp_game_server.rb', line 145

def port
  return @server.addr[1]
end


163
164
165
166
167
168
# File 'lib/mjai/tcp_game_server.rb', line 163

def print_backtrace(ex, io = $stderr)
  io.printf("%s: %s (%p)\n", ex.backtrace[0], ex.message, ex.class)
  for s in ex.backtrace[1..-1]
    io.printf("        %s\n", s)
  end
end

#process_one_gameObject



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/mjai/tcp_game_server.rb', line 96

def process_one_game()
  
  game = nil
  success = false
  begin
    (game, success) = play_game(@players)
  rescue => ex
    print_backtrace(ex)
  end
  
  begin
    for player in @players
      player.close()
    end
  rescue => ex
    print_backtrace(ex)
  end
  
  begin
    for pid in @pids
      Process.waitpid(pid)
    end
  rescue => ex
    print_backtrace(ex)
  end
  
  @num_finished_games += 1
  
  if success
    on_game_succeed(game)
  else
    on_game_fail(game)
  end
  puts()
  
  @pids = []
  @players = []
  if @num_finished_games >= @params[:num_games]
    exit()
  else
    start_default_players()
  end
  
end

#runObject



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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/mjai/tcp_game_server.rb', line 27

def run()
  puts("Listening on host %s, port %d" % [@params[:host], self.port])
  puts("URL: %s" % self.server_url)
  puts("Waiting for %d players..." % self.num_tcp_players)
  @pids = []
  begin
    start_default_players()
    while true
      Thread.new(@server.accept()) do |socket|
        error = nil
        begin
          socket.sync = true
          socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
          send(socket, {
              "type" => "hello",
              "protocol" => "mjsonp",
              "protocol_version" => 3,
          })
          line = socket.gets()
          if !line
            raise(LocalError, "Connection closed")
          end
          puts("server <- player ?\t#{line}")
          message = JSON.parse(line)
          if message["type"] != "join" || !message["name"] || !message["room"]
            raise(LocalError, "Expected e.g. %s" %
                JSON.dump({"type" => "join", "name" => "noname", "room" => @params[:room]}))
          end
          if message["room"] != @params[:room]
            raise(LocalError, "No such room. Available room: %s" % @params[:room])
          end
          @mutex.synchronize() do
            if @players.size >= self.num_tcp_players
              raise(LocalError, "The room is busy. Retry after a while.")
            end
            @players.push(TCPPlayer.new(socket, message["name"]))
            puts("Waiting for %s more players..." % (self.num_tcp_players - @players.size))
            if @players.size == self.num_tcp_players
              Thread.new(){ process_one_game() }
            end
          end
        rescue JSON::ParserError => ex
          error = "JSON syntax error: %s" % ex.message
        rescue SystemCallError => ex
          error = ex.message
        rescue LocalError => ex
          error = ex.message
        end
        if error
          begin
            send(socket, {"type" => "error", "message" => error})
            socket.close()
          rescue SystemCallError
          end
        end
      end
    end
  rescue Exception => ex
    for pid in @pids
      begin
        Process.kill("INT", pid)
      rescue => ex2
        p ex2
      end
    end
    raise(ex)
  end
end

#send(socket, hash) ⇒ Object



157
158
159
160
161
# File 'lib/mjai/tcp_game_server.rb', line 157

def send(socket, hash)
  line = JSON.dump(hash)
  puts("server -> player ?\t#{line}")
  socket.puts(line)
end

#server_urlObject



141
142
143
# File 'lib/mjai/tcp_game_server.rb', line 141

def server_url
  return "mjsonp://localhost:%d/%s" % [self.port, @params[:room]]
end

#start_default_playersObject



149
150
151
152
153
154
155
# File 'lib/mjai/tcp_game_server.rb', line 149

def start_default_players()
  for command in @params[:player_commands]
    command += " " + self.server_url
    puts(command)
    @pids.push(fork(){ exec(command) })
  end
end