Very Simple C++ TCP Echo Server

14,527

Solution 1

The terms "simple" and "C++ TCP Echo Server" don't belong together in the same sentence. There is no such thing.

The sample that you are looking at is probably as close to "simple" as you're going to get (if you want to get into the nitty-gritty). Using a library that handles all the heavy lifting for you would make things easier (but far less educational). I would probably check out Boost.Asio (and the example Blocking TCP Echo Server example).

If things aren't making sense, you should probably go back and brush up on your C++ network programming until you get to the point that things start clicking.

Solution 2

To learn network programming, I highly recommend you see if you can buy, beg, borrow, or steal (stay away from my copy) a copy of Richard W Stevens book Unix Network Programming (note that after the first edition, the subsequent editions are split into volumes, so make sure you get the right volume for TCP/IP).

I found it to be a detailed resource for learning TCP programming, primarily on Unix/POSIX systems. If memory servers, it has some code for a TCP echo client and server written in C that it uses for some of its examples. You can find the source code for the book here - dig around the Makefile and source code in the tcpcliserv dir:

http://www.kohala.com/start/unpv12e.html

Edit: I realize its not a C++ version you asked for, but if I'm right that your end goal is learning network programming, learning it in C should be a fine stepping stone to C++ ....

B

Solution 3

I would recommend that you look into the boost framework -- it provides the same kind of "indispensable utility classes" that the JDK provides to Java programmers.

There are many tutorials available for various aspects of boost. Here's one on getting started with the asynchronous i/o components.

If you want to jump straight into the (very simple) server socket example, here it is.

Share:
14,527
tree-hacker
Author by

tree-hacker

Updated on June 05, 2022

Comments

  • tree-hacker
    tree-hacker almost 2 years

    I am new to C++ network programming but have experience with Java sockets etc.

    I have been trying to write a simple TCP echo server in C++ but cannot really make any progress. I've tried looking at some code like at http://cs.baylor.edu/~donahoo/practical/CSockets/practical/ but cannot get anything to work.

    Can anyone give me some simple C++ code to get started with for something like a TCP echo server? I do not really understand how to even get started.

    Thanks in advance.