繼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