back to scratko.xyz
aboutsummaryrefslogtreecommitdiff
path: root/README.md
blob: 89881a7d8a77cf3d96b656fd38a570fda3fa49e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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.