C++流扩展 streambuff-转载

C++流扩展 streambuff

  • 结合socket流的扩展
    • 转载链接

结合socket流的扩展

#include 

/////               out
//no buffer
	class SocketOutStreamBuf
		: public std::streambuf
	{
	public:
		SocketOutStreamBuf(SOCKET
			socket) : m_socket(socket) {
		}

	protected:
		int_type overflow(int_type c) {
				if (c != EOF) {
					if (send(m_socket,(char*)&c, 1, 0) <= 0) {
						return EOF;
					}
				}
				return c;
			}

	private:
		SOCKET m_socket;
	};


//has buffer
class SocketOutStreamBuf
	: public std::streambuf
{
public:
	SocketOutStreamBuf(SOCKET
		socket) : m_socket(socket) {
		setp(m_buffer, m_buffer + BufferSize - 1);
	}

	~SocketOutStreamBuf()
	{
		sync();
	}

protected:
	int_type overflow(int_type c) {
			if (c != EOF) {
				*pptr() = c;
				pbump(1);
			}

			if (FlushBuffer() == EOF) {
				return EOF;
			}

			return c;
		}

	int sync()
	{
		if (FlushBuffer() == EOF) {
			return -1;
		}

		return 0;
	}

private:
	int FlushBuffer()
	{

		int len = pptr() - pbase();

		if (send(m_socket, m_buffer, len, 0) <= 0) {
			return EOF;
		}

		pbump(-len);

		return len;
	}

	SOCKET m_socket;
	static const int BufferSize = 512;
	char m_buffer[BufferSize];
};


//use
{
	SOCKET socket;
	…

	SocketOutStreamBuf outBuf(socket);
	std::ostream outStream(&outBuf);

	std::string line;
	while (std::getline(std::cin, line)) {
		outStream << line << std::endl;
	}
}


///  in
//no buffer
	class SocketInStreamBuf
		: public std::streambuf
	{
	public:
		SocketInStreamBuf(SOCKET
			socket) : m_socket(socket) {
		}

		int_type underflow() {
				char c;
				if (recv(m_socket, &c, 1, MSG_PEEK) <= 0) {
					return EOF;
				}

				return c;
			}

		int_type uflow() {
				char c;
				if (recv(m_socket, &c, 1, 0) <= 0) {
					return EOF;
				}

				return c;
			}

	private:
		SOCKET
			m_socket;
	};

	//has buffer
	class SocketInStreamBuf
		: public std::streambuf
	{
	public:
		SocketInStreamBuf(SOCKET
			socket) : m_socket(socket) {
			setg(m_buffer, m_buffer, m_buffer);
		}

		int_type underflow() {
				int recvLen = recv(m_socket, m_buffer, BufferSize, 0);

				if (recvLen <= 0) {
					return EOF;
				}

				setg(m_buffer, m_buffer, m_buffer + recvLen);

				return *gptr();
			}

	private:
		SOCKET m_socket;
		static const int BufferSize = 512;
		char m_buffer[BufferSize];
	};


	//use
	{
		SOCKET socket;

		SocketInStreamBuf inBuf(socket);
		std::istream socketStream(&inBuf);

		std::stringline;
		while (std::getline(socketStream, line)) {
			std::cout << line << std::endl;
		}
	}

转载链接

https://blog.csdn.net/turkeyzhou/article/details/8983379

你可能感兴趣的:(C++)