![](/img/trans.png)
[英]Regular expressions: a character cannot show more than 4 times in a sequence
[英]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()
兩次使用之間未reset
您的io_service
。
如果要在停止后再次使用相同的io_service
,則必須調用reset
成員函數。
write_to_server("123");
io_service.reset();
write_to_server("456");
也就是說,這不是設計全部內容的最佳方法,您可能應該使用相同的io_service
並不要停止它,但是由於io_service
的run
成員函數將是程序的主循環,因此您必須要么在連接回調中一個接一個地發送消息,或者創建某種事件驅動的程序,在該程序中,根據用戶輸入(例如,在stdin或套接字等上讀取)發送消息。 但這僅在您開發更大,更復雜的程序時才應考慮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.