简体   繁体   中英

C++ and network sockets

I have dabbled in C, and I am currently picking up C++.

I want to learn the standard library ( std:: namespace), so I am working on a few projects. One is a simple email program that logs into my local SMTP server and shows my email, and has the ability to send mail. I add a touch of ncurses for that old feel.

The problem is, I haven't been able to find a standard library way to use network sockets. It seems like I have to use network sockets in C sys/socket.h , but then I end up with a file descriptor, which leaves read() and write() and send() function calls. I wanted to be able to use the std::fstream or std::ostream classes. But the open() member functions take a filename, not a file descriptor.

I know that the Boost library has this capability, but templates and such are way over my head, and I want to stick with just the standard library for now.

Before I proceed, I just want to make sure that there isn't a better way to read() and write() to a file descriptor that's been returned by the connect() network socket C function.

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

Your choices are

  1. BSD sockets, if you are on *nix via OS specific libraries
  2. BSD blocking sockets, if you are on Windows, via Winsock
  3. Async sockets, if you are on Windows, via Winsock and the Windows Message Pump
  4. IOCP, if you are on Windows, via Winsock
  5. Boost ASIO, which is portable.
  6. Some other 3rd party library where someone else used one of the above and wrapped it up for you.

Of all of those, it is my personal opinion that, Boost ASIO is the easiest to use. I would recommend at least going through a tutorial on blocking BSD sockets though to get the concepts down.

All of these, except 5 and 6, are going to be very C like. Network programming really isn't a niche where object orientated programming and C++ rule over old C style. You can wrap things, but that'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 in the end, all these implementations are similar, in that you will be sending and receiving bytes of binary data or text.

你可以使用带有套接字的std:::istreamstd::ostream ,你只需编写自己的(或找到一个预先存在的第三方)自定义std::basic_streambuf -derived类,它使用套接字I / O而不是文件I / O,然后您可以通过其构造函数或rdbuf()方法将该类的实例分配给std::(i|o)stream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM