Poco::Net::TCPServer 的 Unix 域套接字

Unix domain sockets with Poco::Net::TCPServer

我使用 Poco::Net::TCPServer 框架创建了一个 TCPServer,它使用一个 unix 域套接字,它似乎可以工作。但是,如果我关闭服务器并再次启动它,我会收到此错误:

Net Exception: Address already in use: /tmp/app.SocketTest

编辑

我有两个问题。第一个是通过在套接字文件上使用 remove() 来回答的。另一个问题是,Poco::Net::TCPServer 框架中的清理是自动执行还是必须手动执行以防止内存泄漏?

这是 TCPServer 的代码:

#include "Poco/Util/ServerApplication.h"
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/File.h"
#include <fstream>
#include <iostream>

using Poco::Net::ServerSocket;
using Poco::Net::StreamSocket;
using Poco::Net::TCPServer;
using Poco::Net::TCPServerConnection;
using Poco::Net::TCPServerConnectionFactory;
using Poco::Net::SocketAddress;
using Poco::Util::ServerApplication;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;



class UnixSocketServerConnection: public TCPServerConnection
    /// This class handles all client connections.
{
public:
    UnixSocketServerConnection(const StreamSocket& s): 
        TCPServerConnection(s)
    {
    }

    void run()
    {
        try
        {
            /*char buffer[1024];
            int n = 1;
            while (n > 0)
            {
                n = socket().receiveBytes(buffer, sizeof(buffer));
                EchoBack(buffer);
            }*/

            std::string message;
            char buffer[1024];
            int n = 1;
            while (n > 0)
            {
                n = socket().receiveBytes(buffer, sizeof(buffer));
                buffer[n] = '[=11=]';
                message += buffer;
                if(sizeof(buffer) > n && message != "")
                {
                    EchoBack(message);
                    message = "";
                }
            }
        }
        catch (Poco::Exception& exc)
        {
            std::cerr << "Error: " << exc.displayText() << std::endl;
        }
        std::cout << "Disconnected." << std::endl;
    }

private:
    inline void EchoBack(std::string message)
    {
        std::cout << "Message: " << message << std::endl;
        socket().sendBytes(message.data(), message.length());
    }
};

class UnixSocketServerConnectionFactory: public TCPServerConnectionFactory
    /// A factory
{
public:
    UnixSocketServerConnectionFactory()
    {
    }

    TCPServerConnection* createConnection(const StreamSocket& socket)
    {
        std::cout << "Got new connection." << std::endl;
        return new UnixSocketServerConnection(socket);
    }

private:

};

class UnixSocketServer: public Poco::Util::ServerApplication
    /// The main application class.
{
public:
    UnixSocketServer(): _helpRequested(false)
    {
    }

    ~UnixSocketServer()
    {
    }

protected:
    void initialize(Application& self)
    {
        loadConfiguration(); // load default configuration files, if present
        ServerApplication::initialize(self);
    }

    void uninitialize()
    {
        ServerApplication::uninitialize();
    }

    void defineOptions(OptionSet& options)
    {
        ServerApplication::defineOptions(options);

        options.addOption(
            Option("help", "h", "display help information on command line arguments")
                .required(false)
                .repeatable(false));
    }

    void handleOption(const std::string& name, const std::string& value)
    {
        ServerApplication::handleOption(name, value);

        if (name == "help")
            _helpRequested = true;
    }

    void displayHelp()
    {
        HelpFormatter helpFormatter(options());
        helpFormatter.setCommand(commandName());
        helpFormatter.setUsage("OPTIONS");
        helpFormatter.setHeader("A server application to test unix domain sockets.");
        helpFormatter.format(std::cout);
    }

    int main(const std::vector<std::string>& args)
    {
        if (_helpRequested)
        {
            displayHelp();
        }
        else
        {
            // set-up unix domain socket
            Poco::File socketFile("/tmp/app.SocketTest");
            SocketAddress unixSocket(SocketAddress::UNIX_LOCAL, socketFile.path());

            // set-up a server socket
            ServerSocket svs(unixSocket);
            // set-up a TCPServer instance
            TCPServer srv(new UnixSocketServerConnectionFactory, svs);
            // start the TCPServer
            srv.start();
            // wait for CTRL-C or kill
            waitForTerminationRequest();
            // Stop the TCPServer
            srv.stop();
        }
        return Application::EXIT_OK;
    }

private:
    bool _helpRequested;
};

int main(int argc, char **argv) {
    UnixSocketServer app;
    return app.run(argc, argv);
}

您无需担心释放内存。一切由图书馆完成。

TCPServer srv(new UnixSocketServerConnectionFactory, svs);
              ^^^

TCPServer根据poco ref

删除了UnixSocketServerConnectionFactory实例

The server takes ownership of the TCPServerConnectionFactory and deletes it when it's no longer needed.

 TCPServerConnection* createConnection(const StreamSocket& socket)
    {
        std::cout << "Got new connection." << std::endl;
        return new UnixSocketServerConnection(socket);
               ^^^
    }

UnixSocketServerConnection 实例也被 Poco library 代码删除:

As soon as the run() method returns, the server connection object is destroyed and the connection is automatically closed.

Poco::File 的问题是 Poco::File 的析构函数无法删除文件,您必须通过 remove 方法明确地执行此操作。