Lua 服务器-客户端聊天示例

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

-- 加载命名空间
local socket = require("socket")
-- 创建一个TCP套接字并将其绑定到本地主机的任何端口
local server = assert(socket.bind("*", 0))
-- 找出操作系统为我们选择的端口
local ip, port = server:getsockname()
-- 打印一条消息,告诉用户如何操作
print("请在本地主机上的端口 " .. port .. " 上键入telnet命令")
print("连接后,您有10秒钟输入一行要回显的内容")
-- 无限循环等待客户端连接

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

    print("客户端发送: " .. line)
  if not err then
    client:send(line .. "\n")
  else
    print('错误')
    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);
--注意下面的换行符
tcp:send("你好,世界\n");

while true do
    local s, status, partial = tcp:receive()
    print(s or partial)
    print("输入要发送的消息")
    local message = io.read()
    print("发送消息" .. message)
    tcp:send(message);
    if status == "closed" then break end

end
tcp:close()

client.lua

现在我不能理解服务器在第一个“你好,世界”后就无法接收到消息,并且当服务器已经连接到客户端时,该如何连接另一个客户端?Lua是否提供收到消息或建立连接的回调函数?

点赞
用户1424244
用户1424244

原文:

You never send any actual end of line to the server, after the first line. Since message will not contain any line end, client:receive() will wait for the end forever (because it reads a line from the socket).

You can try calling server:accept() multiple times to wait for a new client. Combined with a timeout and coroutines, you can serve multiple clients.

翻译:

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

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

2018-10-18 15:05:42