Lua tcp demo

Lua

本来是应该昨天发的,今天补上。

算是最简单的socket例子。

client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
local socket = require("socket")
host = "127.0.0.1"
port = 8383
-- open a tcp connect,
-- method socket.connect(), means client
c = assert (socket.connect (host, port))
c:send ("request...\n")
while (true) do
local s, status, partial = c:receive ()
print(s)
if status == "closed" then break end
c:send ("request...\n")
end
c:close ()

server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
socket = require("socket");
-- IP & port
host = "127.0.0.1";
port = "8383";
-- method socket.bind(), means client
server = assert(socket.bind(host, port));
msg = "from server...\n";
while 1 do
print("server: waitting for connection...");
-- return a client representing
control = assert(server:accept());
while 1 do
command,status = control:receive();
if status == "closed" then break end
print(command);
control:send(msg);
end
end