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.
setup.lua contains the WiFi AP setup details
app.lua contains the logic to run the TCP server and serve the client requests.
conn:send("Hello from Node MCU");
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.
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.
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.
If you every thing is right, you should see something like this when you send a request to the Node.
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)