Skip to content

Day45 - TCP Server with poll() and epoll()

📌 Project Structure

d45-network-socket/
    mytcp_server_poll.c
    mytcp_server_epoll.c
    test_poll.sh

Step 1: Basic TCP Server

  • create socket
  • bind to port
  • listen
  • accept client
  • recv / send

Step 2: poll-based server

Key idea:

poll(server_fd + client_fds)
→ detect readable events

Features:

  • supports multiple clients
  • simple fd array management

Step 3: epoll-based server

Key APIs:

epoll_create1()
epoll_ctl()
epoll_wait()

Flow:

epoll_wait()
→ server_fd → accept
→ client_fd → recv/send

Step 4: Non-blocking mode

Set fd:

fcntl(fd, F_SETFL, O_NONBLOCK)

Step 5: accept loop (drain queue)

while (accept() >= 0)
    add client
if errno == EAGAIN → break

Step 6: recv loop (non-blocking)

while (1):
    recv()

    n > 0 → process
    n == 0 → closed
    n < 0:
        EAGAIN → done
        else → error

Step 7: send (non-blocking simplified)

send()
→ EAGAIN → stop
→ partial send possible

Step 7: TX Queue

struct tx_queue {
    buf
    len
    off
}

Step 8: EPOLLOUT Handling

EPOLLIN:
    recv → tx_queue_set
    enable EPOLLOUT

EPOLLOUT:
    send pending data
    if empty → disable EPOLLOUT

Test Script

bash test_poll.sh

Test coverage:

  • single client
  • multi-client
  • rapid connect/close
  • exceed client count