TCP
Basics
Next up we will be looking at TCP, the Transmission Control Protocol.
TCP is a procotol far more complicated than UDP, as in addition to ports, introduces a handshaking process, a notion of a “connection”, message acknowledgement for reliable transport, flow control, timeouts and a lot of other aspects.
Luckily these aspects are mostly abstracted away by the software we use and we can treat a TCP connection as a reliable pipe where data put in on one side will make it to the other side eventually.
NodeMCU Server
The code snipped below starts a TCP server on the microcontroller board that waits for connections.
clients= {}
function socket_to_cid(socket)
local client_id= nil
-- Go through the list of sockets and
-- find the one matching the requested socket
for cid, client in ipairs(clients) do
if client == socket then
client_id = cid
end
end
return client_id
end
function broadcast(message)
for cid, client in ipairs(clients) do
client:send(message.."\n")
end
print(message)
end
function on_tcp_data(socket, data)
local stripped= data:gsub("\n", "")
local client_id= socket_to_cid(socket)
broadcast("Client "..client_id..": "..stripped)
end
function on_tcp_disconnect(socket, code)
local client_id= socket_to_cid(socket)
table.remove(clients, client_id)
broadcast("Client "..client_id.." disconnected")
end
function on_tcp_connect(socket)
socket:on("receive", on_tcp_data)
socket:on("disconnection", on_tcp_disconnect)
table.insert(clients, socket)
local client_id= socket_to_cid(socket)
broadcast("Client "..client_id.." connected")
end
function setup_tcp()
local server = net.createServer()
server:listen(5000, on_tcp_connect)
print("listening on port 5000")
end
setup_tcp()
Replace the content of you application.lua
with
the code above, upload it, start picocom and reset
the microcontroller.
Netcat client
You can now open a new terminal and
connect to the server using netcat
(note the missing -u
switch compared to UDP).
[user@computer ~]$ nc 192.168.94.158 5000
Task: Using multiple terminals and netcat sessions and the sourcecode find out what the program does.
Task: Edit the program so that the first client can turn on the LED when she sends the “on” command and the second client can turn off the LED when she sends the “off” command.