TCP Server on Node MCU

One of the cool thing about node MCU is with little coding we can achieve complex functionalities. All the complexity is hidden in the library functions.
In this blog we will see how to open a TCP server port and listen for connections. We can achieve server-client communication in two ways.

1. Node MCU can provide a WiFi AP, and client can directly connect to the node using this AP. Once connected Clients can send requests.

Node MCU -TCP Server- AP
Node MCU -TCP Server- AP

setup.lua contains the WiFi AP setup details

local module={}
function module.start()
wifi.setmode(wifi.SOFTAP)
cfg={}
cfg.ssid="esp"
cfg.pwd="XXXXXXXXX"
cfg.channel=6
wifi.ap.config(cfg)
cfd ={}
cfd.ip="192.168.2.1"
cfd.netmask="255.255.255.0"
cfd.gateway="192.168.2.1"
wifi.ap.setip(cfd)
print(wifi.ap.getip())
print(wifi.ap.getmac())
app.start()
end

return module

app.lua contains the logic to run the TCP server and serve the client requests.

local module={}
function module.start()
srv=net.createServer(net.TCP)
print("Server started");
srv:listen(80,"192.168.2.1",function(conn)
conn:on("receive",function(conn,payload)
print(payload)
conn:send("Hello from Node MCU");
end)
end)
end
return module

You can find the files here, flash the files to node and run test.lua.Connect to the “esp” access point, Then open the URL http://192.168.2.1 in your browser to the message from node MCU.

TCP_Server_WiFi_AP
TCP_Server_WiFi_AP

2. Node MCU will connect to a WiFi AP (for example your home WiFi AP). Now the node is present on your LAN. You can just use node IP to send requests.

NodeMCU_WiFi_Client_TCP_Server
NodeMCU_WiFi_Client_TCP_Server

In this method we need to change the setup.lua to connect to WiFi AP. We will add one more file config.lua to store the SSID and Password of your WiFi AP. The app.lua would be same

You can find all required files here. Flash all files to the node, and run test.lua to run the code. You can get the IP of the node form console, send a request to this IP.

TCP_Server_WiFi_client
TCP_Server_WiFi_client

If you every thing is right, you should see something like this when you send a request to the Node.

NodeMCU_Response
NodeMCU_Response

Now we have all the code required, but we need to run it in order to see the output , We create test.lua to run the code. every time you reset your node you need to run this test.lua file. You may use init.lua for this purpose(init.lua will be ran by node on every reset). If you are using the first method please remove the second line(we don’t have the config file in first method)

app = require("app")
config=require("config")
setup = require("setup")
setup.start()

 

10 Comments

Add a Comment

Your email address will not be published. Required fields are marked *