【发布时间】:2017-07-16 09:53:25
【问题描述】:
问题
在LuaSocket Introduction 之后,我设法让server 运行。我还设法从client 端进行连接。但要获得此连接,client 必须知道server 端口号。在示例代码中,server 端口为 0,这意味着:
如果端口为0,系统会自动选择一个临时端口。
我想这种方法有它的优点,但是可怜的client应该怎么知道连接到哪个端口?
问题
如何将临时端口号从server 传递到client?我认为在这个过程中应该没有人为的行为。
代码
服务器(来自LuaSocketIntroduction)
-- load namespace
local socket = require("socket")
-- create a TCP socket and bind it to the local host, at any port
local server = assert(socket.bind("*", 0))
-- find out which port the OS chose for us
local ip, port = server:getsockname()
-- print a message informing what's up
print("Please telnet to localhost on port " .. port)
print("After connecting, you have 10s to enter a line to be echoed")
-- loop forever waiting for clients
while 1 do
-- wait for a connection from any client
local client = server:accept()
-- make sure we don't block waiting for this client's line
client:settimeout(10)
-- receive the line
local line, err = client:receive()
-- if there was no error, send it back to the client
if not err then client:send(line .. "\n") end
-- done with client, close the object
client:close()
end
客户端(关注this answer)
local host, port = "127.0.0.1", 100
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port);
--note the newline below
tcp:send("hello world\n");
while true do
local s, status, partial = tcp:receive()
print(s or partial)
if status == "closed" then break end
end
tcp:close()
【问题讨论】: