我的客户端在连接后接收到来自服务器的所有消息,但服务器的输出始终如下:
Client #1 connected.
first packet error: timeout
Looping client #1
message error: timeout
Looping client #1
message error: timeout
Looping client #1
message error: timeout
...etc...
我已经弄乱了每边的一些价值观。它通常什么也不做,但有时当弄乱服务器的超时值时,它就会使服务器永远挂在客户端上:send()或client:receive()。我永远无法得到它,以便他们两个可以互相交换信息。为什么呢?
我的目标是让每个循环花费最少时间(<2-3ms)的客户端和服务器,这样我就可以花很多时间做其他事情(这是一个更大的程序的一部分,但我把它隔离了在客户端或服务器上更容易测试问题。我无法承受长时间的阻塞呼叫,因此我将超时设置得非常低。
服务器来源:
socket = require("socket");
server = assert(socket.bind("*", 534));
ip, port = server:getsockname();
server:settimeout(0.03);
nClients = 0;
clients = {};
print("Server started.");
while true do
local client, err = server:accept();
if (not err) then
nClients = nClients + 1;
print("Client #"..nClients.." connected.");
clients[nClients] = client;
clients[nClients]:settimeout(0.03);
clients[nClients]:send("test");
local msg, err = clients[nClients]:receive();
if (not err) then
print("we got it");
else
print("first packet error: "..err);
end
end
for i=1,nClients do
if (clients[i] ~= nil) then
print("Looping client #"..i);
local msg, err = clients[i]:receive();
if (not err) then
print("message received: "..msg);
else
print("message error: "..err);
end
clients[nClients]:send("another message");
end
end
socket.sleep(0.01);
end
客户来源:
socket = require("socket");
tcp = assert(socket.tcp());
ip, port = "127.0.0.1", 534;
print("Client started.");
tcp:settimeout(0.03);
tcp:connect(ip, port);
while true do
local a, b, msg = tcp:receive();
if (msg and #msg > 1) then
print("message received: "..msg);
end
tcp:send("message");
socket.sleep(0.01);
end