-1

我正在实现一个简单的客户端-服务器程序。我写的部分内容是:

  int main(void){  
    using namespace boost::asio;
    using namespace std;
     const std::string ip = "localhost";
     const int port       = 10500;
     ip::address addr = ip::address::from_string(ip);
     ip::tcp::endpoint ep(addr, port);
    ip::tcp::iostream s(ep);

     s << "TERMINATE\n" << std::flush;} //This sends Terminate command to the server.
   }
  void function(void){
       s << "TERMINATE\n" << std::flush;} // This part doesn't work.

      }

我是 boost asio 和网络编程的新手。并在 Windows MingGW 上工作。

在上面的代码中,我在 main 函数中声明了 ip 地址,但是当我尝试在 main 之外声明的其他函数中使用它时,它不起作用。带有错误,例如:'s' 未在此范围内声明。如果它是一个普通变量,我会在 main 之外声明它,并且所有其他函数都可以共享。但这不适用于此。您需要在哪里以及如何声明 IP 地址和端口。我假设

using namespace boost::asio;
using namespace std;
const std::string ip = "localhost";
const int port = 10500;
ip::address addr = ip::address::from_string(ip);
ip::tcp::endpoint ep(addr, port);
ip::tcp::iostream s(ep);

以上部分正在做声明。

4

1 回答 1

0

你可以把它变成一个全局变量。就像是,

using namespace boost::asio;
using namespace std;

ip::tcp::iostream s;

int main(void){  
    const std::string ip = "localhost";
    const int port       = 10500;
    ip::address addr = ip::address::from_string(ip);
    ip::tcp::endpoint ep(addr, port);
    s = iostream(ep);

    s << "TERMINATE\n" << std::flush;} //This sends Terminate command to the server.
}
void function(void){
    s << "TERMINATE\n" << std::flush;}
 }

更好的解决方案是将其作为参数传递给您的函数。全局变量通常不好用。

using namespace boost::asio;
using namespace std;

int main(void){  
    const std::string ip = "localhost";
    const int port       = 10500;
    ip::address addr = ip::address::from_string(ip);
    ip::tcp::endpoint ep(addr, port);
    ip::tcp::iostream s(ep);

    function(s);
}
void function(ip::tcp::iostream &s){
    s << "TERMINATE\n" << std::flush;}
 }
于 2012-09-27T00:17:07.003 回答