C ++ and network sockets

I tried in C and now I am typing in C ++.

I want to learn the standard library ( std::

namespace), so I am working on multiple projects. One is simple email that registers with my local SMTP server and shows my email and has the ability to send mail. I am adding ncurses touch for this old feeling.

The problem is that I could not find a standard library way to use network sockets. I feel like I should be using network sockets in C sys/socket.h

, but then I end up with a file descriptor that leaves the read()

and write()

and function calls send()

. I wanted to be able to use classes std::fstream

or std::ostream

. But member functions open()

take a file name, not a file descriptor.

I know the Boost library has this capability, but templates, etc. is over my head and I only want to stick with the standard library.

Before continuing, I just want to make sure there is no better way read()

and write()

describe the file that was returned by the network socket function connect()

.

+3


source to share


2 answers


The standard library does not contain sockets or any kind of networking support.

Your choice

  • BSD sockets if you are on * nix via OS specific libraries
  • BSD blocking sockets if you are on Windows via Winsock
  • Asynchronous sockets if you are on Windows via Winsock and Windows Message Pump
  • IOCP if you are on Windows via Winsock
  • Boost ASIO that is portable.
  • Some other third party library where someone else has used one of the above and wrapped it up for you.


Of these, my personal opinion is that Boost ASIO is the easiest to use. I would recommend at least going through the BSD socket blocking tutorial, if only to understand how to do it.

All of these except 5 and 6 will be very similar to C. Network programming is really not a niche where object oriented programming and C ++ rule over the old C style. You can wrap things up, but it's the best you can hope for ...

You really won't be using fstream or ostream in your socket code. Perhaps in a layer above it, but at the end of the day, all of these implementations are similar in that you will be sending and receiving bytes of binary data or text.

+2


source


You can use std:::istream

and std::ostream

socket, you just have to write your own (or find an existing third-party) user std::basic_streambuf

- a class that uses the socket input and output instead of input-output files and then you can assign an instance of this class std::(i|o)stream

through its constructor or rdbuf()

.



0


source







All Articles