Lesson 9 of 15

TCP Server Simulation

TCP Server Simulation

A TCP server listens on a port, accepts incoming connections, and processes requests. In this lesson, we simulate the server-side behavior of TCP communication.

Server Lifecycle

1. bind(port)    — Reserve a port
2. listen()      — Start accepting connections
3. accept()      — Accept a client connection
4. receive()     — Read data from client
5. send()        — Send response to client
6. close()       — Close connection

Connection Management

A server maintains a list of active connections. Each connection has:

  • A client address (IP:port)
  • A state (LISTENING, CONNECTED, CLOSED)
  • A send/receive buffer

Your Task

Implement a TCPServer class that simulates a TCP server:

  • bind(port) — binds to a port, returns true if successful
  • listen() — starts listening (must be bound first)
  • accept(clientAddr) — accepts a connection, returns a connection ID
  • receive(connId, data) — buffers received data for a connection
  • send(connId, data) — returns the data that would be sent
  • getBuffer(connId) — returns all buffered received data
  • close(connId) — closes a connection
  • getState(connId) — returns connection state
Node.js loading...
Loading...
Click "Run" to execute your code.