gpt4 book ai didi

ruby - ruby 中的 TCPServer,代码卡住了

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:15 24 4
gpt4 key购买 nike

我正在用 ruby​​ 构建一个小游戏来练习编程,到目前为止一切顺利,但我正在尝试实现多人游戏支持,我可以连接到服务器并且可以发送信息但是当我尝试从服务器读取时它只是卡住,我的屏幕完全变黑。我找不到原因,我阅读了用于 TCP 的 gem 的文档,但我不知道,也许我错过了一些东西,但如果你们中的任何人有一些见解,我将非常感激

如果这段代码还不够,这里是repo

https://github.com/jaypitti/ruby-2d-gosu-game

这是客户端代码

class Client
include Celluloid::IO
def initialize(server, port)
begin
@socket = TCPSocket.new(server, port)
rescue
$error_message = "Cannot find game server."
end
end
def send_message(message)
@socket.write(message) if @socket
end
def read_message
@socket.readpartial(4096) if @socket
end
end

这是游戏服务器

require 'celluloid/autostart'
require 'celluloid/io'
class Server
include Celluloid::IO
finalizer :shutdown
def initialize(host, port)
puts "Starting Server on #{host}:#{port}."
@server = TCPServer.new(host, port)
@objects = Hash.new
@players = Hash.new
async.run
end
def shutdown
@server.close if @server
end
def run
loop { async.handle_connection @server.accept }
end
def handle_connection(socket)
_, port, host = socket.peeraddr
user = "#{host}:#{port}"
puts "#{user} has joined the arena."
loop do
data = socket.readpartial(4096)
data_array = data.split("\n")
if data_array and !data_array.empty?
begin
data_array.each do |row|
message = row.split("|")
if message.size == 10
case message[0]
when 'obj'
@players[user] = message[1..9] unless @players[user]
@objects[message[1]] = message[1..9]
when 'del'
@objects.delete message[1]
end
end
response = String.new
@objects.each_value do |obj|
(response << obj.join("|") << "\n") if obj
end
socket.write response
end
rescue Exception => exception
puts exception.backtrace
end
end # end data
end # end loop
rescue EOFError => err
player = @players[user]
puts "#{player[3]} has left"
@objects.delete player[0]
@players.delete user
socket.close
end
end
server, port = ARGV[0] || "0.0.0.0", ARGV[1] || 1234
supervisor = Server.supervise(server, port.to_i)
trap("INT") do
supervisor.terminate
exit
end
sleep

最佳答案

it just freezes and my screen goes completely black. and i cant find the cause

您可以看看的一个好技巧是使用 rbspy 附加到您的进程或 rbtrace看看它卡住时是怎么回事。

您也可以先尝试减少此处的依赖性,然后使用简单的线程池执行此操作,然后再与赛璐珞或事件机器完全异步。

关于ruby - ruby 中的 TCPServer,代码卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com