我有一个应用程序,它像一个客户端,它使用Boost Asio连接到服务器。 它运作良好,但我想改变它的行为。
此刻,当我启动它时,应用程序立即尝试连接到服务器,如果没有发生(因为服务器已关闭),则应用程序无法启动。
我想使用条件案例,以便在运行时决定应用程序何时必须启动与服务器的连接:这样,我可以使用其他应用程序功能,必须连接到服务器。< / p>
我尝试在条件案例中填写创建io_obejct的代码并尝试连接到套接字,但它不起作用:
if (mode == A_CONDITION) {
using boost::asio::ip::tcp;
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), server, boost::lexical_cast<string>(porta));
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
s.connect(*iterator);
}
因为“s”是在if语句中定义的,所以它在其余代码中超出范围,所以我不编译:
在功能
'int main(int, char**)'
中:
/home/user/src/main.cpp:960:26:错误:'s'
未在此范围内声明
/home/user/src/main.cpp:972:60:错误:'s'
未在此范围内声明
/home/user/src/main.cpp:1080:60:错误:'s'
未在此范围内声明
这是因为我使用了三次
boost::asio::write(s, boost::asio::buffer(heading_data, heading_length));
if条件块的外部。
我不能在条件案例块中包含套接字的写入,所以我认为我必须使用's'的全局定义,但我不知道如何执行此操作或者是否有其他更好的解决方案。
我希望你能帮助我:)。
编辑纯粹的可爱: 如果我这样做:
tcp::socket *s = 0;
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), server, boost::lexical_cast<string>(porta));
tcp::resolver::iterator iterator = resolver.resolve(query);
if (mode = FOLLOW_MODE){
s = new tcp::socket(io_service);
s->connect(*iterator);
}
它在编译过程中给出了这些错误:
> In file included from
> /usr/include/boost/asio/write.hpp:526:0,
> from /usr/include/boost/asio/buffered_write_stream.hpp:32,
> from /usr/include/boost/asio/buffered_stream.hpp:26,
> from /usr/include/boost/asio.hpp:34,
> from /home/user/src/main.cpp:9:
> /usr/include/boost/asio/impl/write.ipp:
> In function 'size_t
> boost::asio::write(SyncWriteStream&,
> const ConstBufferSequence&,
> CompletionCondition,
> boost::system::error_code&) [with
> SyncWriteStream =
> boost::asio::basic_stream_socket<boost::asio::ip::tcp>*, ConstBufferSequence =
> boost::asio::const_buffers_1,
> CompletionCondition =
> boost::asio::detail::transfer_all_t,
> size_t = unsigned int]':
> /usr/include/boost/asio/impl/write.ipp:57:71:
> instantiated from 'size_t
> boost::asio::write(SyncWriteStream&,
> const ConstBufferSequence&) [with
> SyncWriteStream =
> boost::asio::basic_stream_socket<boost::asio::ip::tcp>*, ConstBufferSequence =
> boost::asio::const_buffers_1, size_t =
> unsigned int]'
> /home/user/src/main.cpp:980:78:
> instantiated from here
> /usr/include/boost/asio/impl/write.ipp:44:57:
> error: request for member 'write_some'
> in 's', which is of non-class type
> 'boost::asio::basic_stream_socket<boost::asio::ip::tcp>*' make[2]: ***
> [src/CMakeFiles/main.dir/main.cpp.o]
> Error 1 make[1]: ***
> [src/CMakeFiles/main.dir/all] Error 2
> make: *** [all] Error 2
答案 0 :(得分:0)
查看chat_client.cpp
中的handle_commit()
。如果出现错误,请尝试重新连接,而不是关闭连接。
答案 1 :(得分:0)
tcp::socket *s = 0;
if (mode == A_CONDITION) {
s = new tcp::socket(io_service);
s->connect(*iterator);
}
好吗?不要忘记稍后删除s
。