Ruby 从浏览器发送 http 请求给 TCPServer 获取不到内容

EdwardRuby · 2013年06月11日 · 最后由 EdwardRuby 回复于 2013年06月11日 · 3681 次阅读

我按照网上指导 copy 了一个很简单的多线程 TCPServer 运行起来。代码如下 TCPServer.rb

require "socket"

server = TCPServer.open "localhost",2000 server.listen 10000

loop { # Servers run forever Thread.start(server.accept) do |client| client.puts(Time.now.ctime) # Send the time to the client client.puts "Closing the connection. Bye!" client.close # Disconnect from the client puts "one client gone" end }

它给的Client.rb的代码如下

require 'socket' # Sockets are in standard library

hostname = 'localhost' port = 2000 s = TCPSocket.open(hostname, port)

while line = s.gets # Read lines from the socket puts line.chop # And print with platform line terminator end s.close # Close the socket when done

分别运行服务器和客户端是没有问题的。但是我比较困惑的是如果在浏览器里面输入 localhost:2000的时候有时候是好的 可以显示两行信息 Time 和 Closing the connection. Bye! 不停刷新地过程中有时候只会显示第一行,有时候提示页面载入出错(FireFox),不知道这是什么道理。

还有一个很奇怪的地方,我在TCPServer.rb的 loop 循环里面最后加入了一句 puts "one clien gone"可是运行的时候在服务器端的控制台看不到信息,最开始运行的时候是有的,后来不知道怎么弄没了。。。

浏览器的话响应应该遵守 http 协议:

content = "#{Time.now.ctime}\nClosing the connection. Bye!"
client.puts "HTTP/1.1 200 OK"
client.puts "Content-Length: #{content.bytesize}"
client.puts
client.print content

关于"one client gone"的输出问题解决了,任务管理器关掉 ruby.exe 重新跑服务器貌似就好了,rubymine 的控制台看来不靠谱。

#1 楼 @luikore 瞬间明白了,thx

#1 楼 @luikore 不过还有个小困惑,浏览器请求一次会在服务器控制台输出两次"one client gone",而运行client.rb只会有一次输出,firebug 显示只发送了一次请求,这点不大明白。

#4 楼 @EdwardRuby 浏览器会请求 favicon

你可以看看每个请求的第一行:

puts client.read "\r\n"
需要 登录 后方可回复, 如果你还没有账号请 注册新账号