Post

Building a TCP/IP Socket Server for IoT Smart Lighting

Building a TCP/IP Socket Server for IoT Smart Lighting

Project Background

I participated in the 1st Woosong University National SW Club Competition and built an IoT smart lighting system that automatically adjusts brightness based on ambient light levels to save energy.

Components:

  • NodeMCU (ESP8266): Measures ambient brightness via light sensor, controls the light
  • Node.js Server: Acts as a relay for communication
  • Android App: Real-time monitoring and manual control

Problem

I needed real-time communication between the NodeMCU and the Android app. I initially implemented this with HTTP, but ran into issues:

  • The app had to continuously poll the server, which drained the battery
  • State changes on the NodeMCU couldn’t be detected immediately by the app
  • Overall responsiveness was poor

Solution: TCP/IP Socket Communication

I decided to use TCP sockets instead of HTTP.

341986878-2d6e1e09-381f-40c7-be49-4a78a26b2fb5.png

Node.js Server (net module)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const net = require('net');

const clients = [];

const server = net.createServer((socket) => {
    clients.push(socket);
    
    socket.on('data', (data) => {
        // Broadcast received data to other clients
        clients.forEach(client => {
            if (client !== socket) {
                client.write(data);
            }
        });
    });
    
    socket.on('close', () => {
        const index = clients.indexOf(socket);
        clients.splice(index, 1);
    });
});

server.listen(3000);

Both the NodeMCU and the Android app connect to this server via TCP, and the server relays messages between them.


Results

  • Light sensor changes were instantly reflected in the app
  • Manual controls from the app reached the NodeMCU in real-time
  • Battery consumption dropped significantly compared to HTTP polling

Lessons Learned

  • I got to experience the difference between HTTP and TCP sockets firsthand
  • Sockets are the way to go when you need real-time communication
  • Choosing the right communication method for your use case matters

From developing the 2nd place award-winning project (President’s Award) at the 1st Woosong University National SW Club Competition.

This post is licensed under CC BY 4.0 by the author.