2018-09-27 23:56:48 +02:00
|
|
|
/*
|
|
|
|
* IXSocket.h
|
|
|
|
* Author: Benjamin Sergeant
|
|
|
|
* Copyright (c) 2017-2018 Machine Zone, Inc. All rights reserved.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <string>
|
|
|
|
#include <functional>
|
|
|
|
#include <mutex>
|
2018-10-01 23:46:11 +02:00
|
|
|
#include <atomic>
|
2018-09-27 23:56:48 +02:00
|
|
|
|
2018-11-02 01:02:49 +01:00
|
|
|
#include "IXEventFd.h"
|
2018-12-15 01:28:11 +01:00
|
|
|
#include "IXCancellationRequest.h"
|
2018-11-02 01:02:49 +01:00
|
|
|
|
2018-09-27 23:56:48 +02:00
|
|
|
namespace ix
|
|
|
|
{
|
|
|
|
class Socket {
|
|
|
|
public:
|
|
|
|
using OnPollCallback = std::function<void()>;
|
|
|
|
|
2018-12-30 06:53:33 +01:00
|
|
|
Socket(int fd = -1);
|
2018-09-27 23:56:48 +02:00
|
|
|
virtual ~Socket();
|
|
|
|
|
|
|
|
void configure();
|
|
|
|
|
|
|
|
virtual void poll(const OnPollCallback& onPollCallback);
|
|
|
|
virtual void wakeUpFromPoll();
|
|
|
|
|
|
|
|
// Virtual methods
|
|
|
|
virtual bool connect(const std::string& url,
|
|
|
|
int port,
|
2018-12-10 02:56:20 +01:00
|
|
|
std::string& errMsg,
|
2018-12-15 01:28:11 +01:00
|
|
|
const CancellationRequest& isCancellationRequested);
|
2018-09-27 23:56:48 +02:00
|
|
|
virtual void close();
|
|
|
|
|
|
|
|
virtual int send(char* buffer, size_t length);
|
|
|
|
virtual int send(const std::string& buffer);
|
|
|
|
virtual int recv(void* buffer, size_t length);
|
|
|
|
|
2019-01-02 16:45:07 +01:00
|
|
|
// Blocking and cancellable versions, working with socket that can be set
|
|
|
|
// to non blocking mode. Used during HTTP upgrade.
|
|
|
|
bool readByte(void* buffer,
|
|
|
|
const CancellationRequest& isCancellationRequested);
|
|
|
|
bool writeBytes(const std::string& str,
|
|
|
|
const CancellationRequest& isCancellationRequested);
|
2019-01-03 01:08:32 +01:00
|
|
|
std::pair<bool, std::string> readLine(const CancellationRequest& isCancellationRequested);
|
2019-01-02 16:45:07 +01:00
|
|
|
|
2019-01-05 02:28:13 +01:00
|
|
|
static int getErrno();
|
2018-10-09 06:42:45 +02:00
|
|
|
static bool init(); // Required on Windows to initialize WinSocket
|
|
|
|
static void cleanup(); // Required on Windows to cleanup WinSocket
|
|
|
|
|
2018-09-27 23:56:48 +02:00
|
|
|
protected:
|
2018-10-09 06:42:45 +02:00
|
|
|
void closeSocket(int fd);
|
|
|
|
|
2018-09-27 23:56:48 +02:00
|
|
|
std::atomic<int> _sockfd;
|
|
|
|
std::mutex _socketMutex;
|
2018-11-02 01:02:49 +01:00
|
|
|
EventFd _eventfd;
|
2018-09-27 23:56:48 +02:00
|
|
|
};
|
|
|
|
}
|