ruby服务器-发出doing-if-then-else检查来自客户端的输入数据
这是我的代码(下面是我的问题): 所以我试着:ruby服务器-发出doing-if-then-else检查来自客户端的输入数据,ruby,server,client,messages,Ruby,Server,Client,Messages,这是我的代码(下面是我的问题): 所以我试着: if msg == code # then do this elsif msg == code2 # then do this # etc 但它不起作用。 我尝试过用nodervcr替换msg,但仍然没有结果。 奇怪的是,它显然得到了消息,而msg does=客户端发送的内容。。但它的作用就好像这个变量立即消失一样。我对ruby不熟悉。请帮助,谢谢。您的代码中有一些问题。但主要的问题是,当你使用像Telnet这样的东西时,你很可能是在输
if msg == code
# then do this
elsif msg == code2
# then do this
# etc
但它不起作用。我尝试过用
nodervcr
替换msg
,但仍然没有结果。奇怪的是,它显然得到了消息,而msg does=客户端发送的内容。。但它的作用就好像这个变量立即消失一样。我对ruby不熟悉。请帮助,谢谢。您的代码中有一些问题。但主要的问题是,当你使用像Telnet这样的东西时,你很可能是在输入 因此,您需要发送“码字”+CRLF(码字\r\n)。这与您的支票不同:msg==“codeword” 您应该做的是从这些字符中删除输入(strip)。它移除CRLF,然后工作 记住。变量赋值为=(单)比较为双== 以下为工作代码:
require "socket"
server = TCPServer.open("127.0.0.1", 2000)
loop {
Thread.start(server.accept) do |nodervcr| # Thread, not thread
msg = nodervcr.gets
# puts(msg)
p msg # use this so see all the invisiable chars
if msg.strip == "codeword" # stip the input
puts("codeword!")
else
puts("not codeword")
end
# Note this part works: it sends the server a message and it displays it
# You would think a simple if then else statement could redirect it according to the imcoming message from the client; which is my issue.
end
}
(客户端向服务器发送一条消息,而不是服务器lol),因此为了澄清问题,服务器获取并显示消息。我只想能够根据传入的消息调用“函数”(或者是ruby中调用的方法?)(如果msg=this,那么就这样做,如果msg=that,那么就这样做,等等。请将您正在使用的条件调用添加到代码中,以及您的意思“变量立即死亡”-您还可以显示您尝试访问变量的位置吗?例如,在循环中确定。如果msg=“codeword”,则为函数名称。该名称应调用方法或函数,或将其称为(批处理中的标签)-问题是它没有。将条件放在if语句下面的下一行也没有任何作用。因此,我所说的变量似乎立即消失。它无法识别它。我可以将代码字发送到服务器,它只是忽略它,就像它从未发生过一样。需要“socket”server=TCPServer.open(“localhost”,2000)循环{thread.start(server.accept)do | nodervcr | msg=nodervcr.gets put(msg)if msg=“codeword”put(“codeword!”)else put(“not codeword!”)end}
require "socket"
server = TCPServer.open("127.0.0.1", 2000)
loop {
Thread.start(server.accept) do |nodervcr| # Thread, not thread
msg = nodervcr.gets
# puts(msg)
p msg # use this so see all the invisiable chars
if msg.strip == "codeword" # stip the input
puts("codeword!")
else
puts("not codeword")
end
# Note this part works: it sends the server a message and it displays it
# You would think a simple if then else statement could redirect it according to the imcoming message from the client; which is my issue.
end
}