简体   繁体   English

双向读取数据 TCPServer Ruby

[英]Read data both ways TCPServer Ruby

im new in Ruby and Im trying to set up a TCPServer and a Client, but Im having trouble getting the data from the client to the server because for some reason when the client connects, the connection is freezed inside the while loop.我是 Ruby 的新手,我试图设置 TCPServer 和客户端,但我无法将数据从客户端获取到服务器,因为由于某种原因,当客户端连接时,连接在 while 循环内被冻结。 Here is the code:这是代码:

server.rb服务器.rb

require "socket"
server = TCPServer.new 1234
test = ""

loop do
  session = server.accept
  puts "Entering enter code herewhile loop."
  while line = session.gets
    puts "Inside while loop"
    test << line
  end
    puts "Finished reading data"

    puts "Data recieved - #{test}" # Read data from client
    session.write "Time is #{Time.now}" # Send data to clent
    session.close
end

client.rb客户端.rb

require "socket"

socket = TCPSocket.open("localhost", 1234)
socket.puts "Sending data.." # Send data to server
while(line = socket.gets)
  puts line
end # Print sever response
socket.close

The server prints "Inside while loop" one time, and then for some reason it never prints "Finished reading data" until I manually end the client connection, after the client ends the connection the server prints everything OK.服务器打印一次“内部while循环”,然后由于某种原因它永远不会打印“完成读取数据”,直到我手动结束客户端连接,客户端结束连接后服务器打印一切正常。 How can I make this code work?我怎样才能使这段代码工作? Thanks!谢谢!

IO#gets is a blocking call. IO#gets是一个阻塞调用。 It waits for either a new line from the underlying I/O stream, or the end of the stream.它等待来自底层 I/O stream 的新行或 stream 的结尾。 (in which case it returns nil ) (在这种情况下它返回nil

In server.rb you haveserver.rb你有

while line = session.gets
  puts "Inside while loop"
  test << line
end

session.gets reads one line from your client, prints some debug info and appends the line to test . session.gets从您的客户端读取一行,打印一些调试信息并将该行附加到test It then attempts to read another line from the client.然后它尝试从客户端读取另一行

Your client.rb however never sends a seconds line, nor does it close the stream.但是,您的client.rb不会发送秒行,也不会关闭 stream。 It sends a single line:它发送一行:

socket.puts "Sending data.." # Send data to server

and then waits for a response:然后等待响应:

while(line = socket.gets)
  puts line
end

which never comes because the server is sitting in the while loop, waiting for more data from the client.这永远不会出现,因为服务器正处于while循环中,等待来自客户端的更多数据。

You can solve this by calling close_write after all data has been sent:您可以通过在发送完所有数据后调用close_write来解决此问题:

socket.puts "Sending data.." # Send data to server
socket.close_write           # Close socket for further writing

Calling close_write instead of close allows you to still read from the socket.调用close_write而不是close允许您仍然从套接字读取。 It will also cause the server's session.gets to return nil , so it can get out of its loop.它还将导致服务器的session.gets返回nil ,因此它可以退出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM