Course contentsShow
← Computer Science
Lesson 1545 of 2,87235. Application Layer ProtocolsFree lesson

Sending and Receiving Data with TCP

Learn how to send and receive data through TCP sockets using send/recv or write/read operations.

Sending and Receiving Data with TCP

You'll learn how to transmit and receive data through established TCP socket connections using fundamental system calls.

The Core Idea

Once a TCP connection is established (via accept() on the server or connect() on the client), you have an open channel for bidirectional communication. Think of it like a phone call: after dialing and connecting, both parties can now speak and listen. The socket file descriptor acts as your communication handle—you write data into it to send, and read from it to receive.

Primary Operations

Sending Data

Use send() or write() to push bytes through the socket:

  • send(sockfd, buffer, length, flags) – TCP-specific, allows optional flags
  • write(sockfd, buffer, length) – Generic file descriptor operation

Both functions return the number of bytes actually sent. Important: they may send fewer bytes than requested if the send buffer fills up, so check the return value and loop if necessary.

Receiving Data

Use recv() or read() to pull bytes from the socket:

  • recv(sockfd, buffer, length, flags) – TCP-specific with optional flags
  • read(sockfd, buffer, length) – Generic file descriptor operation

These return the number of bytes received (or 0 if the connection closed, -1 on error). TCP is a stream protocol—data arrives as a continuous byte stream without message boundaries, so you must handle framing yourself.

The Data Flow

When you send data, it enters the TCP send buffer, gets segmented, acknowledged, and reassembled at the receiver. The receive buffer holds incoming data until you read it. These operations block by default until data is available or sent.

Key Takeaway: Use send()/recv() or write()/read() on connected TCP sockets to exchange byte streams, always checking return values since partial sends/receives are possible and TCP delivers data as an unstructured stream.