服务器程序
local socket = require("socket")
local server = socket.try(socket.bind("*", 1234))
local ip, port = server:getsockname()
while 1 do
local client = server:accept()
client:settimeout(10)
local line, err = client:receive()
print (line)
print("Enter input:")
if not err then client:send(io.read().."\n") end
client:close()
end
客户计划
local host, port = "*", 1234
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port);
tcp:send("Connection Established\n");
while 1 do
local s, status, partial = tcp:receive()
print(s or partial)
print("Enter input:")
tcp:send(io.read().."\n");
if status == "closed" then break end
end
tcp:close()
服务器程序可以将消息发送到客户端,但客户端无法向服务器发送消息。有没有办法做到这一点.. ??
答案 0 :(得分:1)
我没有足够的声誉来评论,但是在10秒钟或服务器发送消息后,以先到者为准,服务器关闭连接。在服务器发送消息之前,客户端不会尝试发送消息,并且您编写代码的方式服务器此时会立即关闭连接。如果你希望两者进行沟通,你最好在循环之外接受客户端,如下所示:
服务器程序
local socket = require("socket")
local server = socket.try(socket.bind("*", 1234))
local ip, port = server:getsockname()
local client = server:accept()
client:settimeout(10)
while 1 do
local line, err = client:receive()
print (line)
print("Enter input:")
if not err then client:send(io.read().."\n") end
end
client:close()
现在,这就提出了服务器缺少代码来实现客户端断开连接并需要找到新客户端的问题,但实现起来并不困难。