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. The system automatically adjusts light brightness based on ambient light levels to save energy.

Components:

  • NodeMCU (ESP8266): Measures brightness with light sensor, controls lighting
  • Node.js Server: Relay server for communication
  • Android App: Real-time monitoring and manual control

Problem

Real-time communication between NodeMCU and the Android app was needed. Initially implemented with HTTP, but there were issues:

  • App had to continuously poll the server, draining battery
  • When NodeMCU state changed, the app couldn’t detect it immediately
  • Lacked real-time responsiveness

Solution: TCP/IP Socket Communication

Decided to implement TCP socket communication instead of HTTP.

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 NodeMCU and the Android app connect to this server via TCP, and the server relays messages between them.


Results

  • Light sensor value changes were immediately reflected in the app
  • Manual light control from the app was delivered to NodeMCU in real-time
  • Reduced battery consumption compared to HTTP polling

Lessons Learned

  • Felt the difference between HTTP and TCP sockets
  • Socket communication is suitable when real-time updates are needed
  • Choosing the right communication method for the situation matters

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

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