当我在main内部进行TCPServer的初始化时,它可以工作,当我尝试使用startServer()函数启动它时,它不起作用,我的意思是我无法与腻子建立连接。

我在这里做错了什么?

谢谢你的帮助。

class EchoConnection : public TCPServerConnection {
public:
EchoConnection(const StreamSocket& s)
    : TCPServerConnection(s) {}

void reply(char buffer[])
{
    bzero(buffer, 256);
    std::string myWord = "myWord\n\r";
    strcpy(buffer, myWord.c_str());
}

void run() {
    StreamSocket& ss = socket();
    try {
        char buffer[256];
        int n = ss.receiveBytes(buffer, sizeof(buffer));
        while (n > 0) {
            reply(buffer);
            ss.sendBytes(buffer, sizeof(buffer));
            n = ss.receiveBytes(buffer, sizeof(buffer));
        }
    }
    catch (Poco::Exception& exc)
    { std::cerr << "EchoConnection: " << exc.displayText() << std::endl; }
}
};

void startServer()
{
    Poco::Net::TCPServer srv(new Poco::Net::TCPServerConnectionFactoryImpl<EchoConnection>, 8089);
    srv.start();

    SocketAddress sa("localhost", srv.socket().address().port());
    StreamSocket ss(sa);
    std::string data("hello, world");
    ss.sendBytes(data.data(), (int)data.size());
    char buffer[256] = { 0 };
    int n = ss.receiveBytes(buffer, sizeof(buffer));
    std::cout << std::string(buffer, n) << std::endl;
}

int main(int argc, char** argv) {

    Poco::Net::TCPServer srv(new Poco::Net::TCPServerConnectionFactoryImpl<EchoConnection>, 8089);
    srv.start();

    SocketAddress sa("localhost", srv.socket().address().port());
    StreamSocket ss(sa);
    std::string data("hello, world");
    ss.sendBytes(data.data(), (int)data.size());
    char buffer[256] = { 0 };
    int n = ss.receiveBytes(buffer, sizeof(buffer));
    std::cout << std::string(buffer, n) << std::endl;

    //  startServer(8089);

    ModuleData modData;
    modData.ModuleNumber = 1;
    modData.ModuleTypeId = 1;

    string test = modData.serialize();

    ifstream dataFile;
    dataFile.open("ModuleData.dat");
    if (dataFile.is_open())
    {
        string line;
        while (getline(dataFile, line))
        {
            cout << line << std::endl;
        }
        dataFile.close();
    }

    while (1)
    {

    }

    srv.stop();
}

最佳答案

startServer函数的末尾,srv对象被删除。 TCPServer使用自己的线程,但是可以在TCPServer的析构函数中完成工作。

查看〜TCPServer的实现

TCPServer::~TCPServer() {
try {
    stop();
    _pDispatcher->release();
...
}

并查看stop方法的实现
void TCPServer::stop() {
  if (!_stopped)
  {
      _stopped = true;    // !!
      _thread.join();     // waiting for thread
      _pDispatcher->stop();
  }
}

线程函数的主体位于run方法中
void TCPServer::run()
{
  while (!_stopped)      // this flag was set by stop method
  {
     ... // body of thread function
  }
}
stop方法将_stopped设置为true,因此线程完成工作。

关于c++ - Poco TCPServer无法在主服务器外部启动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47739412/

10-13 06:31