不能通过asio将消息写入服务器两次以上
Cannot write the message to the server more than two times by asio
在对这个页面进行了一些调查之后,我尝试编写一个小程序,将消息写入用python脚本开发的本地服务器。到目前为止一切顺利,问题是我只能将消息写入服务器一次。
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>
std::string input;
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::socket sock(io_service);
boost::array<char, 4096> buffer;
void connect_handler(const boost::system::error_code &ec)
{
if(!ec){
boost::asio::write(sock, boost::asio::buffer(input));
}
}
void resolve_handler(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it)
{
if (!ec){
sock.async_connect(*it, connect_handler);
}
}
void write_to_server(std::string const &message)
{
boost::asio::ip::tcp::resolver::query query("127.0.0.1", "9999");
input = message;
resolver.async_resolve(query, resolve_handler);
io_service.run();
}
int main()
{
write_to_server("123");
write_to_server("456");
}
以下是python脚本
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
您的io_service
在两个用途之间不是reset
。
如果您想在停止后再次使用相同的io_service
,则必须调用reset
成员函数。
write_to_server("123");
io_service.reset();
write_to_server("456");
说,这不是最好的方法来设计整个东西,您应该使用相同的io_service
从未停止,但由于run
io_service
成员函数将主循环程序,你需要发送你的消息一个又一个正确连接回调,或创造某种事件驱动的程序,你发送消息基于用户的输入(如读stdin或一个套接字等)。但是,只有在开发更大更复杂的程序时才应该考虑这一点。
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- Winsock:回显服务器回复两次,当时我刚刚将其编程为执行一次send()调用
- c ++:TCP服务器"bind"功能失败(errno 98),如果我在两次连续应用程序启动之间没有等待足够的时间
- 不能通过asio将消息写入服务器两次以上
- Boost异步服务器接受两次连接