继LuaSocket
Introduction我设法让server
运行。我也设法从client
方连接。但要获得此连接,client
必须知道端口号server
。在示例代码中,server
端口为0,表示:
如果端口为0,系统将自动选择一个临时端口。
我想这种方法有它的优点,但穷人client
应该知道连接到哪个端口?
问题
如何从server
临时端口号沟通client
?我认为在这个过程中不应该有任何人为的行为。
代码
服务器(从LuaSocket
Introduction)
-- 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()
那么我该如何选择服务器端口呢?换句话说:我是否确保我选择的端口不被其他应用程序使用?如果我选择一个使用alreaby的应用程序,那么应用程序将具有优先权? – Siemkowski
如果一个进程绑定到特定的IP:端口,则任何其他进程将在尝试绑定到该特定的IP:端口时失败。 – Prabhu