【问题标题】:Communicate server port to client? (TCP)与客户端通信服务器端口? (TCP)
【发布时间】: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()

【问题讨论】:

    标签: tcp lua luasocket


    【解决方案1】:

    如何将临时端口号从服务器传送到客户端?我假设在这个过程中不应该有人为行为。我假设在这个过程中应该没有人为行为。

    你是对的。服务器示例很奇怪。服务器通常应绑定到特定端口。它不应该是短暂的。这样当服务器重新启动时,客户端会连接到与之前相同的端口。否则,如果服务器端口不断变化,客户端将会丢失。

    客户端,确实可以绑定到临时端口(他们通常这样做)。服务器应该绑定到特定的。

    【讨论】:

    • 那我该如何选择服务器端口呢?换句话说,如何:我是否确保我选择的端口没有被其他应用程序使用?如果我选择一个已经在使用的端口,哪个应用程序将具有优先权?
    • 如果一个进程绑定到特定 IP:Port,任何其他进程在尝试绑定到该特定 IP:Port 时都会失败。
    【解决方案2】:

    在 TCP/IP 连接中,服务器总是绑定到一个已知端口。不允许服务器绑定到端口 0。它必须在已知端口上可用,以便客户端可以连接到它。您应该更改示例以将服务器绑定到固定端口,然后在客户端连接函数中使用该固定端口。

    【讨论】:

    • 这是来自官方LuaSocket - 包作者 - 页面的示例。我认为会误导初学者。
    • 是的,我知道。我正在使用该软件包。服务器必须有一个可见的绑定端口。
    猜你喜欢
    • 2023-03-18
    • 2012-04-19
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2018-10-18
    • 1970-01-01
    相关资源
    最近更新 更多