2017-02-25 138 views
0

問題將服務器端口與客戶端通信? (TCP)

LuaSocketIntroduction我設法讓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() 

回答

1

如何通信的ephem從服務器到客戶端的端口號?我認爲在這個過程中不應該有任何人爲的行爲。我認爲在這個過程中不應該有任何人爲的行動。

你是對的。服務器的例子很奇怪。服務器通常應綁定到特定的端口。它不應該是短暫的。因此,當服務器重新啓動時,客戶端將連接到與之前相同的端口。否則,如果服務器端口不斷變化,客戶端將會丟失。

客戶端確實可以綁定到臨時端口(他們通常會這樣做)。服務器應該綁定到特定的服務器。

+0

那麼我該如何選擇服務器端口呢?換句話說:我是否確保我選擇的端口不被其他應用程序使用?如果我選擇一個使用alreaby的應用程序,那麼應用程序將具有優先權? – Siemkowski

+1

如果一個進程綁定到特定的IP:端口,則任何其他進程將在嘗試綁定到該特定的IP:端口時失敗。 – Prabhu

1

在TCP/IP連接中,服務器始終綁定到已知端口。服務器不允許綁定到端口0.它必須在已知端口上可用,以便客戶端可以連接到它。您應該更改示例以將服務器綁定到固定端口,然後在客戶端連接功能中使用該固定端口。

+0

是的,我知道。我正在使用該軟件包。服務器必須有一個可見的綁定端口。 –