好的,所以我正在构建一个服务器来玩战争游戏作为一项任务。我的服务器需要从两个不同的套接字获取输入,这就是我被卡住的地方。我已将我的套接字存储为键,将我的播放器存储为哈希值,但我无法在主程序中获取套接字。
我可以将哈希放在我的主程序中,但我不能只获得一个套接字以便我可以告诉我的程序从中读取。这是我的课程和我正在进行的测试:
require 'minitest/autorun'
require 'socket'
require_relative 'WarGame_Class.rb'
require_relative 'ModifiedPlayer_Class.rb'
require_relative 'DeckClass.rb'
class WarServer
def initialize(host, port)
@socket_server = TCPServer.new(host, port)
@players = [Player.new, Player.new]
@deck = CardDeck.new
@deck.deal_cards(@players[0].cards, @players[1].cards)
game = WarGame.new
@clients = {} # keys are sockets, values are players
end
def read_client_keys
@clients.key[0] #does not work
end
def close
@socket_server.close
end
def capture_input(player) ##input client to get what they wrote
@input = @clients.keys[0].read_nonblock(1000) # arbitrary max number of bytes
end
def accept_client
#Hash here to link client to player? (or game?)
client = @socket_server.accept
@clients[client] = @players[@clients.size]
# puts "clients key 0: #{@clients.keys[0]}"
puts
# puts "clients values: #{@clients.values}"
if @clients.size == 2
start_game#####################!!!! Starts game if two clients can put client messages in start game
end
end
def start_game ##############!!!
@clients.keys[0].puts "Welcome to War. Please press enter to play your card"
@clients.keys[1].puts "Welcome to War. Please press enter to play your card"
end
end
class MockWarClient
def initialize
@socket = TCPSocket.new('localhost', 2012)
end
def output
@output
end
def capture_output #need to add (socket)? How else read from specific socket?
@output = @socket.read_nonblock(1000) # arbitrary max number of bytes
rescue
@output = "capture_output error."
end
def capture_input
end
end
class WarServerTest < MiniTest::Unit::TestCase
def setup #This would be like our INITIALIZE Function
#anything is available through out all tests (i.e., instance vars)
@war_server = WarServer.new('localhost', 2012)
end
def teardown
@war_server.close
end
def test_server_capture_output_from_client
client_1 = MockWarClient.new
@war_server.accept_client
client_2 = MockWarClient.new
@war_server.accept_client
#can output @war_server.read_client_keys, though, if I take out the argument to pass in.
#puts "Test_Server_output @client keys #{@war_server.read_client_keys(player)}" #cient_1?
puts "Test_Server_output @client keys #{@war_server.read_client_keys}"
# I NEED TO JUST BE ABLE TO GET *ONE* KEY SO I CAN READ FROM THE SOCKET
@warserver.capture_input
refute(@war_server.input.empty)
end
end
答案 0 :(得分:0)
您必须使用#keys[0]
(或#keys.first
)来选择哈希的第一个键。
函数#key(val)
执行不同的操作,返回与哈希中val
出现对应的键。
http://www.ruby-doc.org/core-2.0.0/Hash.html#method-i-key-3F
def read_client_keys
@clients.keys[0] # this should work
end