客户端连接的 host 设置为‘localhost’的时候,可以用本机连接上。 host 设置为‘127.0.0.1’的时候,用本机都无法连接上。 host 设置为‘192.168.0.xxx’的时候也是本机和其他机器都无法连接。 代码如下,有大神指教下是怎么回事吗……?
服务端
require 'socket'
module CloudHash
class Server
def initialize(port)
@server = TCPServer.new(port)
puts "Listening on port #{@server.local_address.ip_port}"
@storage = {}
end
def start
Socket.accept_loop(@server) do |connection|
handle(connection)
connection.close
end
end
def handle(connection)
request = connection.read
connection.write process(request)
end
def process(request)
command, key, value = request.split("/")
case command.upcase
when 'GET'
@storage[key]
when 'SET'
@storage[key] = value
end
end
end
end
server = CloudHash::Server.new(4481)
server.start
客户端
require 'socket'
module CloudHash
class Client
class << self
attr_accessor :host, :port
end
def self.get(key)
request "GET/#{key}"
end
def self.set(key, value)
request "SET/#{key}/#{value}"
end
def self.request(string)
@client = TCPSocket.new(host, port)
@client.print(string)
@client.close_write
@client.read
end
end
end
CloudHash::Client.host = 'localhost'
CloudHash::Client.port = 4481