back to scratko.xyz
aboutsummaryrefslogtreecommitdiff

Simple Multithreaded TCP Counter Server

This project implements a basic multithreaded TCP server in C that maintains a shared integer counter. Clients can connect to the server and send commands to modify or query the counter value concurrently.

Features

  • Handles multiple clients concurrently using POSIX threads (pthread).
  • Synchronizes access to a shared counter variable with a mutex to avoid race conditions.
  • Supports three commands from clients:
    • up — increments the counter by 1.
    • down — decrements the counter by 1.
    • show — returns the current value of the counter.
  • Responds with "Ok\n" to confirm up and down commands.
  • Responds with the counter value followed by newline for show command.
  • Handles unknown commands gracefully with an error message.
  • Uses semaphores for thread synchronization on startup.
  • Detaches threads after creation to clean up resources automatically.

How It Works

  • The server listens on a TCP port specified as a command-line argument.
  • For each incoming client connection, it spawns a detached worker thread.
  • The worker thread reads commands line-by-line from the client socket.
  • Commands are parsed and processed with proper mutex locking on the shared counter.
  • The connection closes when the client disconnects.

Usage

Build with:

git clone https://git.scratko.xyz/threaded-tcp-counter
gcc -pthread -o tcp_counter_server server.c

Run:

./tcp_counter_server <port>

Example:

./tcp_counter_server 12345

Then connect with telnet or netcat:

telnet localhost 12345

Send commands like:

up
show
down
show

Limitations and Notes

  • The server currently uses a single shared thread_data struct, which may cause race conditions if multiple clients connect simultaneously. Improvements could include per-thread data allocation.
  • The server supports only simple line-based commands.
  • No security or authentication.
  • Minimal error handling for simplicity.