Files
hate/Socket.h
2025-11-22 16:25:58 +01:00

86 lines
1.5 KiB
C++

#pragma once
#include "RC.h"
#include <streambuf>
#include <istream>
#include <ostream>
class SocketStreamBuf;
class ISocketStream;
class OSocketStream;
class SocketStream;
class Socket
{
public:
Socket();
Socket(size_t socket) : _sock(socket) {};
virtual ~Socket();
void bind(unsigned short port) { bind(nullptr, port); }
void bind(const char* address, unsigned short port);
void listen(int backlog = 1024);
Socket accept();
int read(void* buffer, int size);
int write(const char* string);
int write(const void* data, int size);
void end();
size_t handle() const { return _sock; }
private:
size_t _sock;
RC _rc;
};
class SocketStreamBuf : public std::streambuf
{
public:
SocketStreamBuf(Socket sock) : _sock(sock), _buf() {}
virtual ~SocketStreamBuf();
virtual int underflow();
virtual int overflow(int c);
virtual int sync();
private:
Socket _sock;
// Read buffer
char _c = 0;
// Send buffer
enum { _buf_size_max = 1024 };
char _buf[_buf_size_max] = { 0 };
int _buf_size = 0;
};
class ISocketStream : public std::istream
{
public:
ISocketStream(Socket& sock) : std::istream(new SocketStreamBuf(sock)) {}
virtual ~ISocketStream() { delete rdbuf(); }
};
class OSocketStream : public std::ostream
{
public:
OSocketStream(Socket& sock) : std::ostream(new SocketStreamBuf(sock)) {}
virtual ~OSocketStream() { delete rdbuf(); }
};
class SocketStream : public std::iostream
{
public:
SocketStream(Socket& sock) : std::iostream(new SocketStreamBuf(sock)) {}
virtual ~SocketStream() { delete rdbuf(); }
};