Home > Blockchain >  Server socket doesn't work properly - "accept is already open"
Server socket doesn't work properly - "accept is already open"

Time:12-09

I've tried to separate my server socket in a singleton. Here's the code:

ServerSocket.h

#pragma once
#include <asio.hpp>
#include <iostream>

using asio::ip::tcp;

class ServerSocket
{
public:
    ServerSocket(ServerSocket& otherSingleton) = delete;
    void operator=(const ServerSocket& copySingleton) = delete;

    tcp::acceptor* InitAcceptor();
    tcp::socket* InitSocket();
    void StartServerSocket();
    void SendData(std::string);
    std::array<char, 5000> RecieveData();

    static ServerSocket* GetInstance();
private:
    static ServerSocket* instance;

    tcp::acceptor* acceptor;
    tcp::socket* socket;
    asio::io_context io_context;

    ServerSocket() {
        acceptor = InitAcceptor();
        socket = InitSocket();
    }

    ~ServerSocket()
    {
        std::cout << "Server closed";
    }
};

ServerSocket.cpp

#include "ServerSocket.h"

tcp::acceptor* ServerSocket::InitAcceptor()
{
    try
    {
        tcp::acceptor* acceptor = new tcp::acceptor(io_context, tcp::endpoint(tcp::v4(), 27015));

        return acceptor;
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

tcp::socket* ServerSocket::InitSocket()
{
    try
    {
        tcp::socket* socket = new tcp::socket(io_context);

        return socket;
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

void ServerSocket::StartServerSocket()
{
    try
    {
        std::cout << "Server started";
        for (;;)
        {
            acceptor->accept(*socket);
        };
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

std::array<char, 5000> ServerSocket::RecieveData()
{
    try {
        std::array<char, 5000> buf;
        asio::error_code error;

        size_t len = socket->read_some(asio::buffer(buf), error);
        buf[len] = '\0';
        return buf;
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

ServerSocket* ServerSocket::instance(nullptr);

ServerSocket* ServerSocket::GetInstance()
{
    if (instance == nullptr)
    {
        instance = new ServerSocket();
    }
    return instance;
}

Server socket starts, I get:

Server started

when a client connects, I get:

accept: Already open 

and the server stops.

I think the error comes from the acceptor being in a for function. But according to the docs, it should work this way. (or at least that's how I understand - enter image description here

  • Related