diff options
author | scratko <m@scratko.xyz> | 2025-08-12 04:22:39 +0300 |
---|---|---|
committer | scratko <m@scratko.xyz> | 2025-08-12 04:22:39 +0300 |
commit | 9ff6c4496557fca79f800ae8da9961e8aebece11 (patch) | |
tree | 71f9c6b41451547a77a0412c3fbf4101d6efefaa | |
parent | 0c12d9c3fd09f4881eb80d8f2b632ab3310f6010 (diff) | |
download | threaded-tcp-counter-master.tar.gz threaded-tcp-counter-master.tar.bz2 threaded-tcp-counter-master.zip |
-rw-r--r-- | README.md | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/README.md b/README.md new file mode 100644 index 0000000..89881a7 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# 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: + +```bash +git clone https://git.scratko.xyz/threaded-tcp-counter +gcc -pthread -o tcp_counter_server server.c +``` +Run: + +```bash +./tcp_counter_server <port> +``` + +Example: +```bash +./tcp_counter_server 12345 +``` +Then connect with telnet or netcat: +```bash +telnet localhost 12345 +``` +Send commands like: + +```bash +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. + |