Summary - Networking
- C++ course
- Advanced
- Lesson 60/83
- 5 min
Combine TCP client/server and Asio to write an echo server.
Summary: the echo server concept
In this summary we combine the socket, TCP client/server and Boost.Asio concepts in an echo server idea. An echo server sends back exactly what the client sends; it is the classic first example of network programming.
An echo server follows these steps: create a socket (socket), bind to a port (bind), wait for connections (listen), accept a client (accept), receive data (recv), send the same data back (send). With Boost.Asio these steps are done asynchronously. This lesson puts the basic socket and Asio setup together; the real echo logic comes in later projects.
Practice Write the echo server skeleton
Add #include <sys/socket.h> and #include <boost/asio.hpp>. Create a TCP socket with int sock = socket(AF_INET, SOCK_STREAM, 0);. Define boost::asio::io_context io;. Print std::cout << "Echo ready";.
Starter code
#include <iostream>
// Add the socket and Asio headers
int main() {
// Create socket and io_context
return 0;
}Sample solution
#include <iostream>
#include <sys/socket.h>
#include <boost/asio.hpp>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
boost::asio::io_context io;
std::cout << "Echo ready";
return 0;
}Expected output
Echo ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the socket call
int sock = ____(AF_INET, SOCK_STREAM, 0);
int sock = socket(AF_INET, SOCK_STREAM, 0);
Explanation: socket(AF_INET, SOCK_STREAM, 0) creates a TCP socket.
2 What does an echo server do?
- It compresses the data
- It deletes the data
- It encrypts the data
- It sends the data back unchanged Correct answer
Explanation: An echo server sends received data back unchanged.
3 Match the step to its role
| Term | Meaning |
|---|---|
socket() |
Creates a socket |
bind() |
Binds to a port |
listen() |
Waits for connections |
accept() |
Accepts a client |