Skip to main content

How to Write a Simple TCP Socket Server Echo Program in VC++

In this blog post, I will show you how to write a simple TCP socket server echo program in VC++. A TCP socket server echo program is a program that listens on a specific port, accepts connections from clients, and echoes back any data received from the clients. This is a useful way to test the basic functionality of TCP sockets and learn how to use the Winsock API in VC++.

If you are interested in my TCP software development, consulting or training services, please feel free to contact me.  

contact email: tcpfast@gmail.com

What is a TCP Socket?

A TCP socket is a communication endpoint that uses the Transmission Control Protocol (TCP) to exchange data reliably and orderly over a network. TCP is one of the core protocols of the Internet Protocol Suite, and it provides reliable, ordered, and error-checked delivery of data between applications running on different machines.

A TCP socket is defined by the IP address of the machine and the port number it uses. The IP address is a unique identifier of the machine on the network, and the port number is a 16-bit number that identifies the specific application or service on the machine. For example, the well-known port number for HTTP is 80, and the well-known port number for FTP is 21.

A TCP socket can be either a server socket or a client socket. A server socket is a socket that listens for incoming connections from client sockets. A client socket is a socket that initiates a connection to a server socket. A TCP connection is established when a client socket and a server socket agree to communicate with each other. A TCP connection is identified by a four-tuple: the IP address and port number of the client socket, and the IP address and port number of the server socket.

How to Write a TCP Socket Server Echo Program in VC++

To write a TCP socket server echo program in VC++, we need to use the Winsock API, which is a set of functions and data structures that provide access to the Windows Sockets implementation. The Winsock API is based on the Berkeley Sockets API, which is a standard interface for network programming in Unix-like systems.

The basic steps to write a TCP socket server echo program in VC++ are:

- Initialize the Winsock library using the `WSAStartup` function.
- Create a TCP server socket using the `socket` function.
- Bind the server socket to a specific port number using the `bind` function.
- Listen for incoming connections using the `listen` function.
- Accept a client connection using the `accept` function.
- Receive data from the client using the `recv` function.
- Echo the data back to the client using the `send` function.
- Close the client socket using the `closesocket` function.
- Repeat steps 5 to 8 for each client connection.
- Close the server socket using the `closesocket` function.
- Clean up the Winsock library using the `WSACleanup` function.

The following is the complete code of the TCP socket server echo program in VC++, with some comments to explain the functionality:

  1. // EchoServer.cpp : Defines the entry point for the console application.
  2. //
  3. #include <iostream>
  4. #include <winsock2.h> // Include the Winsock API header file
  5. #pragma comment(lib, "ws2_32.lib"// Link the Winsock library
  6. #define MAX_CLIENTS 10 // The maximum number of concurrent clients
  7. #define BUFFER_SIZE 1024 // The size of the buffer for receiving and sending data
  8. #define ECHO_PORT 4444 // The port number for the echo server
  9. // A function to print the error message and exit the program
  10. void error(const char* msg)
  11. {
  12.     std::cerr << msg << ": " << WSAGetLastError() << std::endl// Print the error code
  13.     exit(1); // Terminate the program
  14. }
  15. // A function to handle the client connection
  16. DWORD WINAPI clientHandler(LPVOID lpParam)
  17. {
  18.     SOCKET clientSock = (SOCKET)lpParam; // Cast the parameter to SOCKET
  19.     char buffer[BUFFER_SIZE]; // A buffer to store the data
  20.     int recvSize; // The number of bytes received
  21.     std::string data; // The data received
  22.     std::string echo; // The data to be echoed back
  23.     while (true)
  24.     {
  25.         // Receive data from the client
  26.         recvSize = recv(clientSock, buffer, BUFFER_SIZE, 0);
  27.         // Check if the connection is closed or an error occurred
  28.         if (recvSize == 0 || recvSize == SOCKET_ERROR)
  29.         {
  30.             std::cout << "Client disconnected." << std::endl;
  31.             closesocket(clientSock); // Close the socket
  32.             return 0// Exit the thread
  33.         }
  34.         // Convert the buffer to a string object
  35.         data = std::string(buffer, recvSize);
  36.         // Prepend "server echo:" to the data
  37.         echo = "server echo:" + data;
  38.         // Send the data back to the client
  39.         send(clientSock, echo.c_str(), echo.length(), 0);
  40.     }
  41.     return 0// Exit the thread
  42. }
  43. int main(int argc, char* argv[])
  44. {
  45.     // Initialize the Winsock library
  46.     WSADATA wsaData;
  47.     if (WSAStartup(MAKEWORD(22), &wsaData) != 0)
  48.     {
  49.         error("Failed to initialize Winsock");
  50.     }
  51.     // Create a TCP server socket
  52.     SOCKET serverSock = socket(AF_INET, SOCK_STREAM, 0);
  53.     if (serverSock == INVALID_SOCKET)
  54.     {
  55.         error("Failed to create socket");
  56.     }
  57.     // Construct the server address structure
  58.     sockaddr_in serverAddr;
  59.     serverAddr.sin_family = AF_INET; // Internet address family
  60.     serverAddr.sin_addr.s_addr = INADDR_ANY; // Any incoming interface
  61.     serverAddr.sin_port = htons(ECHO_PORT); // Echo server port
  62.     // Bind the socket to the server address
  63.     if (bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
  64.     {
  65.         error("Failed to bind the socket");
  66.     }
  67.     // Listen for incoming connections
  68.     if (listen(serverSock, MAX_CLIENTS) == SOCKET_ERROR)
  69.     {
  70.         error("Failed to listen on the socket");
  71.     }
  72.     std::cout << "Echo server is running on port " << ECHO_PORT << std::endl;
  73.     // Accept the client connections
  74.     SOCKET clientSock; // The accepted client socket
  75.     sockaddr_in clientAddr; // The address of the client
  76.     int clientLen = sizeof(clientAddr); // The length of the address
  77.     HANDLE clientThread; // The handle of the thread for the client
  78.     while (true)
  79.     {
  80.         // Accept a client connection
  81.         clientSock = accept(serverSock, (sockaddr*)&clientAddr, &clientLen);
  82.         if (clientSock == INVALID_SOCKET)
  83.         {
  84.             error("Failed to accept a client connection");
  85.         }
  86.         std::cout << "Client connected: " << inet_ntoa(clientAddr.sin_addr) << std::endl;
  87.         // Create a new thread to handle the client connection
  88.         clientThread = CreateThread(NULL0, clientHandler, (LPVOID)clientSock, 0NULL);
  89.         if (clientThread == NULL)
  90.         {
  91.             error("Failed to create a thread for the client");
  92.         }
  93.     }
  94.     // Close the server socket
  95.     closesocket(serverSock);
  96.     // Clean up the Winsock library
  97.     WSACleanup();
  98.     return 0;
  99. }


How to Test the TCP Socket Server Echo Program in VC++

To test the TCP socket server echo program in VC++, we need to compile and run the program, and then use a TCP client program to connect to the server and send data. One simple way to do this is to use the `telnet` command, which is a terminal emulator that can communicate with TCP servers.

You can compile this C++ program in an IDE (Integrated Development Environment) or use the cl.exe command to compile it on the console. Taking VS2019 as an example, cl.exe is located in:
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.22.27905\bin\Hostx86\x86\cl.exe"

It is recommended to use IDE to generate exe

The following steps show how to test the TCP socket server echo program in VC++ using the `telnet` command:

- Open a command prompt and navigate to the folder where the EchoServer.cpp file is located.
- Compile the program using the following command: `cl EchoServer.cpp ws2_32.lib`
- Run the program using the following command: `EchoServer`
- Open another command prompt and use the `telnet` command to connect to the server on port 4444: `telnet localhost 4444`
- Type any data and press enter. The server should echo back the same data with "server echo:" prepended to it.
- To close the connection, type `Ctrl+]` and then `quit`.

The following is an example of the output of the test:

  1. C:\Users\tcpBuilder\Desktop>cl EchoServer.cpp ws2_32.lib
  2. Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x86
  3. Copyright (C) Microsoft Corporation.  All rights reserved.
  4. EchoServer.cpp
  5. Microsoft (R) Incremental Linker Version 14.00.24215.1
  6. Copyright (C) Microsoft Corporation.  All rights reserved.
  7. /out:EchoServer.exe
  8. EchoServer.obj
  9. ws2_32.lib
  10. C:\Users\tcpBuilder\Desktop>EchoServer
  11. Echo server is running on port 4444
  12. C:\Users\tcpBuilder\Desktop>telnet localhost 4444
  13. Connecting To localhost...Could not open connection to the host, on port 4444: Connect failed
  14. Hello
  15. server echo:Hello
  16. World
  17. server echo:World
  18. Ctrl+]
  19. telnet> quit
  20. Connection to host lost.
  21. C:\Users\tcpBuilder\Desktop>

If you have any questions or feedback, please feel free email to me (tcpfast@gmail.com) or leave a comment below. 

Thank you for reading.


Comments

Popular posts from this blog

How to Set Buffer Size for TCP Socket Programming in C++

TCP socket programming is a common way to communicate between different processes or machines over the network. However, one of the challenges of TCP socket programming is how to set the buffer size for sending and receiving data. The buffer size determines how much data can be stored in memory before it is transmitted or processed. If the buffer size is too small, the data may be fragmented or lost, resulting in poor performance or errors. If the buffer size is too large, the memory may be wasted or the data may be delayed, affecting the responsiveness or timeliness of the communication. In this blog post, I will explain how to set the buffer size for TCP socket programming in C++, and provide some examples of how to use the relevant functions and parameters. The buffer size for TCP socket programming in C++ can be set by using the setsockopt function, which allows the programmer to change the options for a socket. The setsockopt function has the following prototype: int setsockopt...

How to Fix TCP Socket Error Code 10061 in C++, Python, and Java

If you are interested in my TCP socket software development, consulting or training services, please feel free to contact me.   contact email: tcpfast@gmail.com TCP  socket error code 10061 is a common network connection error that indicates that the target server refused the connection request. This usually happens when you try to connect to a service that is not running on the target host, or when your network firewall or antivirus software blocks the port communication. In this blog post, I will explain the possible causes of this error and how to fix it in different programming languages, such as C++, Python, and Java. Possible Causes of TCP Socket Error Code 10061 There are several possible reasons why you may encounter TCP error code 10061 when you try to establish a TCP connection with a server. Some of the most common ones are: - You are using the wrong port number or protocol type (TCP or UDP) to connect to the server. For example, if the server is listening on p...

Example: A TCP Socket Echo Server in Python

Introduction TCP (Transmission Control Protocol) is one of the most widely used protocols in the Internet. It provides reliable, ordered, and error-checked delivery of data between applications running on different devices. A TCP socket is an endpoint of a TCP connection, which is identified by an IP address and a port number. A TCP socket can send and receive data to and from another TCP socket over the network. In this article, I will show you how to write a simple TCP socket echo server in Python, which is a program that listens for incoming connections from TCP socket clients, and echoes back whatever data it receives from them. This program can be useful for testing the functionality and performance of TCP sockets, as well as learning the basics of socket programming in Python. Requirements To write and run this program, you will need the following: - A computer with Python 3 installed. You can download Python 3 from [here]. - A text editor or an IDE (Integrated Development Enviro...