Lua 服务器客户端聊天示例

Lua Server Client Chat Example

我正在尝试使用 lua 创建一个简单的聊天应用程序,以下是我的文件

-- 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

local client = server:accept()
client:setoption("keepalive", true)
while 1 do  
  local line, err = client:receive()

    print(line .. 'sent by client')
  if not err then 
    client:send(line .. "\n") 
  else
    print('error')
    print(err)
  end
end
client:close()

server.lua

local host, port = "127.0.0.1",arg[1]
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)
    print("enter message to send")
    local message = io.read()
    print("sending message" .. message)
    tcp:send(message);
    if status == "closed" then break end


end
tcp:close()

client.lua

现在我无法理解服务器在第一个 hello world 之后没有收到消息,以及当服务器已经连接到客户端时我如何连接另一个客户端,lua 是否提供任何回调接收或建立连接?

您永远不会在第一行之后向服务器发送任何实际的行尾。由于 message 不包含任何行结束,client:receive() 将永远等待结束(因为它从套接字读取 line)。

您可以尝试多次调用 server:accept() 以等待新客户。结合超时和协程,您可以为多个客户端提供服务。