Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Building a TCP Chat Client-Server in C++ on Linux (Reptilian) – Step-by-Step Socket Programming Tutorial

Learn how to build a simple TCP client-server application in C++ using Linux socket programming. This step-by-step tutorial covers creating sockets, binding, listening, accepting connections, and exchanging messages. Perfect for COP4600 students and anyone learning network programming.

socket programming C++ TCP client server Linux COP4600 networking Linux socket tutorial C++ network programming socket bind listen accept client server chat C++ Reptilian socket assignment beginner socket programming TCP/IP socket example C++ server client code network programming for students multiplayer game networking chat application C++ Linux socket API COP4600 ex9 solution guide

Introduction to Socket Programming in C++ on Linux

Socket programming is the backbone of network communication. Whether you're building a chat app, a multiplayer game, or a distributed system, understanding how to create a client-server model using TCP sockets is essential. In this tutorial, we'll walk through creating a simple client and server program in C++ that run on the same Linux host (Reptilian) and exchange messages. This exercise is inspired by the COP4600 Ex9: Networking 2 assignment, but we'll focus on the core concepts without solving the assignment directly.

Think of it like building a two-way radio: the server listens on a specific frequency (port), and the client tunes in to that frequency to start talking. Once connected, both can send and receive messages. This is exactly how many modern apps work – from Discord to online gaming – just at a lower level.

Prerequisites: What You Need to Know

Before diving in, you should be comfortable with C++ basics (variables, loops, functions) and have a Linux environment (like Reptilian) with a C++ compiler (g++). We'll use standard POSIX socket APIs, so no external libraries are needed. If you're new to networking, don't worry – we'll explain every step.

Step 1: Setting Up the Server

The server's job is to listen for incoming client connections. Here's the high-level flow:

  1. Create a socket with socket().
  2. Bind it to an IP address and port using bind().
  3. Listen for connections with listen().
  4. Accept a client connection with accept().
  5. Send and receive messages using send() and recv().
  6. Close the socket.

We'll write a server that takes a port number as a command-line argument (e.g., ./server 1234). The server will wait for a client, then send a welcome message and print whatever the client sends.

Server Code Walkthrough

First, include necessary headers: <iostream>, <string>, <cstring>, <sys/socket.h>, <netinet/in.h>, <unistd.h>. Then, create a socket:

int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) { perror("socket failed"); exit(EXIT_FAILURE); }

Next, bind to an address. We'll use INADDR_ANY to listen on all interfaces:

struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
    perror("bind failed");
    exit(EXIT_FAILURE);
}

Now listen and accept:

if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); }
int addrlen = sizeof(address);
int new_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
if (new_socket < 0) { perror("accept"); exit(EXIT_FAILURE); }

Once connected, send a welcome message and receive a message from the client:

char buffer[1024] = {0};
const char* welcome = "Welcome to the server running on REPTILIAN";
send(new_socket, welcome, strlen(welcome), 0);
printf("Welcome message sent\n");
int valread = read(new_socket, buffer, 1024);
printf("Client says: %s\n", buffer);

Finally, close sockets: close(new_socket); close(server_fd);

Step 2: Writing the Client

The client also takes a port number and connects to the server running on localhost. Flow:

  1. Create a socket.
  2. Connect to the server's IP and port using connect().
  3. Send a message and receive the server's response.
  4. Close the socket.

Client Code Walkthrough

Create socket same as server. Then set up the server address structure with IP 127.0.0.1 (localhost) and the port:

struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);

Connect:

if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
    perror("connect failed");
    exit(EXIT_FAILURE);
}

Send a message and receive the welcome:

const char* msg = "Hello from client";
send(sock, msg, strlen(msg), 0);
printf("Message sent\n");
char buffer[1024] = {0};
int valread = read(sock, buffer, 1024);
printf("Server says: %s\n", buffer);

Close the socket: close(sock);

Step 3: Compiling and Running

Compile both programs with g++:

g++ server.cpp -o server
g++ client.cpp -o client

Run the server first in one terminal: ./server 1234. Then open another terminal and run the client: ./client 1234. You should see the server print the client's message and the client print the server's welcome message.

Common Issues and Troubleshooting

If you get bind failed: Address already in use, wait a moment or use a different port. On Reptilian, you might need to use setsockopt with SO_REUSEADDR. Also, ensure both programs use the same port number. If the client can't connect, check that the server is running and listening. This is a classic networking exercise – debugging these issues is part of the learning process.

Real-World Connections: From Gaming to AI

Socket programming isn't just for assignments. Every time you play an online game like Valorant or Fortnite, your client is communicating with a game server using sockets. Chat apps like WhatsApp and Slack rely on similar principles. Even AI chatbots like ChatGPT use sockets to handle concurrent user requests. Understanding this low-level communication helps you appreciate how data travels across the internet.

SEO Keywords and Learning Path

If you're searching for more resources, try keywords like: socket programming in C++ tutorial, TCP client server example Linux, COP4600 networking exercise, Linux socket programming for beginners. This tutorial covers the essentials, but you can extend it by adding multithreading to handle multiple clients, or by using non-blocking sockets for asynchronous communication.

Conclusion

You've now built a basic TCP client-server application in C++. This foundation opens doors to more advanced networking topics like HTTP servers, WebSockets, and distributed systems. Practice by modifying the messages, adding error handling, or creating a simple chat room. Happy coding!