我正在尝试用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
现在我无法理解服务器在第一个问候世界之后没有收到消息,并且在服务器已经连接到客户端的情况下如何连接另一个客户端,lua是否提供任何回调来建立接收或连接?
答案 0 :(得分:1)
在第一行之后,您永远不会将任何实际的行尾发送到服务器。由于message
将不包含任何行尾,因此client:receive()
将永远等待行尾(因为它会从套接字读取 line )。
您可以尝试多次致电server:accept()
以等待新客户。结合超时和协程,您可以为多个客户提供服务。