Server Code:
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 |
#include <iostream> #include <thread> #include <vector> #include <cstring> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #define PORT 8080 #define BUFFER_SIZE 1024 void handleClient(int clientSocket) { char buffer[BUFFER_SIZE]; int bytesRead; while ((bytesRead = recv(clientSocket, buffer, sizeof(buffer) - 1, 0)) > 0) { buffer[bytesRead] = '\0'; std::cout << "Client: " << buffer << std::endl; send(clientSocket, buffer, bytesRead, 0); // Echo back the message } close(clientSocket); } int main() { int serverSocket, clientSocket; struct sockaddr_in serverAddr, clientAddr; socklen_t clientAddrLen = sizeof(clientAddr); serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_port = htons(PORT); if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("Bind failed"); close(serverSocket); exit(EXIT_FAILURE); } if (listen(serverSocket, 3) < 0) { perror("Listen failed"); close(serverSocket); exit(EXIT_FAILURE); } std::cout << "Server listening on port " << PORT << std::endl; while ((clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen)) >= 0) { std::thread(handleClient, clientSocket).detach(); } if (clientSocket < 0) { perror("Accept failed"); } close(serverSocket); return 0; } |
Client Code:
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 |
#include <iostream> #include <cstring> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #define PORT 8080 #define BUFFER_SIZE 1024 int main() { int sock = 0; struct sockaddr_in serv_addr; char buffer[BUFFER_SIZE] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cerr << "Socket creation error" << std::endl; return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { std::cerr << "Invalid address/ Address not supported" << std::endl; return -1; } if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) { std::cerr << "Connection Failed" << std::endl return -1; } std::cout << "Connected to the server." << std::endl; while (true) { std::string message; std::cout << "Enter message (type 'exit' to quit): "; std::getline(std::cin, message); if (message == "exit") { break; } send(sock, message.c_str(), message.size(), 0); char buffer[BUFFER_SIZE] = {0}; int bytesRead = recv(sock, buffer, sizeof(buffer) - 1, 0); if (bytesRead > 0) { buffer[bytesRead] = '\0'; std::cout << "Server: " << buffer << std::endl; } else { std::cerr << "Connection closed or error occurred." << std::endl; break; } } close(sock); return 0; } |
Explanation:
Server Code:
- Setup:
- Creates a socket using
socket()
. - Configures server address
serverAddr
withAF_INET
(IPv4),INADDR_ANY
(binds to all available interfaces), andPORT
. - Binds the socket to the address using
bind()
. - Listens for incoming connections with
listen()
.
- Creates a socket using
- Handling Clients:
- Uses
accept()
to accept incoming client connections. - Spawns a new thread to handle each client connection. The
handleClient()
function:- Receives messages from the client.
- Prints the received message.
- Sends the same message back to the client (echo server).
- Closes the client socket when done.
- Uses
- Error Handling:
- Checks for errors at each step and prints appropriate error messages using
perror()
.
- Checks for errors at each step and prints appropriate error messages using
Client Code:
- Setup:
- Creates a socket with
socket()
. - Configures server address
serv_addr
withAF_INET
andPORT
. - Converts IP address to binary form with
inet_pton()
and connects to the server usingconnect()
.
- Creates a socket with
- Interaction:
- Sends user input to the server with
send()
. - Receives and prints the server’s response with
recv()
. - Exits the loop if the user types “exit”.
- Sends user input to the server with
- Error Handling:
- Checks for connection errors and displays messages if needed.
How to Run:
Compile and Run the Server:
12g++ -o server server.cpp./serverCompile and Run the Client:
12g++ -o client client.cpp./clientTesting:
- Start the server first.
- Then, run the client.
- Type messages in the client and observe that they are echoed back by the server.
- Checks for connection errors and displays messages if needed.