我是Ruby套接字的新手。我在服务器中有项目,并且我坐在服务器中的插座如下:
require 'socket'
server = TCPServer.open(2000)
loop {
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime)
client.puts "Closing the connection. Bye!"
client.close
end
我想从客户端从项目中运行我的一种方法:
require 'socket'
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets
puts line.chop
puts "hey"
# call helloWorldMethod()
end
s.close
require 'socket'
server = TCPServer.open(2000)
loop do
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime)
client.puts "Closing the connection. Bye!"
client.close
end
end
我相信您的解决方案在TCPSERVER类中
我找到了有关Ruby插座编程的文档
微小的Web浏览器
我们可以使用套接字库来实现任何Internet协议。例如,这里是获取网页内容
的代码
根据您的路由,您可能需要适应URL,它可能是www.yourwebsite.com/users
require 'socket'
host = 'www.tutorialspoint.com' # The web server
port = 80 # Default HTTP port
path = "/index.htm" # The file we want
这是我们发送的HTTP请求以获取文件
您可以在HTTP post
或put
请求
request = "GET #{path} HTTP/1.0rnrn"
socket = TCPSocket.open(host,port) # Connect to server
socket.print(request) # Send request
response = socket.read # Read complete response
# Split response at first blank line into headers and body
headers,body = response.split("rnrn", 2)
print body # And display it
要实现类似的Web客户端,您可以使用诸如NET :: HTTP之类的预构建库与HTTP合作。这是执行以前代码的代码 -
require 'net/http' # The library we need
host = 'www.tutorialspoint.com' # The web server
path = '/index.htm' # The file we want
http = Net::HTTP.new(host) # Create a connection
headers, body = http.get(path) # Request the file
if headers.code == "200" # Check the status code
print body
else
puts "#{headers.code} #{headers.message}"
end