void SerialDevice::readCompleted(const boost::system::error_code& error, const size_t bytesTransferred) { if(!error) { pImpl->result=resultSuccess; pImpl->bytesTransferred=bytesTransferred; return; } //In case a asynchronous operation is cancelled due to a timeout, //each OS seems to have its way to react. #ifdef _WIN32 if(error.value()==995) return; //Windows spits out error 995 #elif defined(__APPLE__) if(error.value()==45) { //Bug on OS X, it might be necessary to repeat the setup //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html pImpl->port.async_read_some( asio::buffer(pImpl->readBuffer,pImpl->readBufferSize), boost::bind(&SerialDevice::readCompleted,this,boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); return; } #else //Linux if(error.value()==125) return; //Linux outputs error 125 #endif pImpl->result=resultError; }
void RemoteClient::readMsg(const boost::system::error_code& err) { if(m_marked_for_delete) { return; } else if(err) { switch(err.value()) { case ENOENT: std::cerr << "QntServer: client socket closed.\n"; break; default: std::cerr << "QntServer: got error reading from socket <" << strerror(err.value()) << ">\n"; } m_server->removeClient(this); m_marked_for_delete = true; m_service.post(boost::bind(&RemoteClient::deleteSelf, this)); return; } ServerMsg *msg = ServerMsg::create(m_next_msg_type, this); if(msg) { msg->read(m_wrapper); m_server->pushMessage(msg); boost::asio::async_read(m_socket, boost::asio::buffer((char*)&m_next_msg_type, 4), boost::bind(&RemoteClient::readMsg, this, boost::asio::placeholders::error)); } else { std::cerr << "QntServer: received unknown message of type <" << m_next_msg_type << ">\n"; std::cerr << "QntServer: closing stream due to unknown error.\n"; m_server->removeClient(this); m_marked_for_delete = true; m_service.post(boost::bind(&RemoteClient::deleteSelf, this)); } }
/*! * * @param error */ void Timer::handle_timer_event(const boost::system::error_code& error, int TimerId) { if (verbose) { std::cout << "handle_timer_event, Timerid = " << TimerId << std::endl; } switch (error.value()) { case boost::system::errc::success: { if (interval_) { timer_func_handler_pntr(TimerId); _TimerList.pop_front(); initiate_timer(); } else { } } break; case boost::system::errc::operation_canceled: { std::cout << "Timer " << TimerId << " cancelled" << std::endl; } break; default: { std::cout << "Assert unexpected case Timer = " << TimerId << " Error = " << error.value() << std::endl; } break; } }
// void TCPSocket::HandleTcpSend(const boost::asio::error& err, size_t bytes_transferred, MyBuffer b) void TCPClientSocket::HandleTcpSend(const boost::system::error_code& err, size_t bytes_transferred) { if ( m_SendQueue.empty() ) { //TRACE("HandleTcpSend %lu %d\n", GetCurrentThreadId(), m_Socket->GetSocket().native()); APP_ERROR("TCPClientSocket::HandleTcpSend invalid empty buffer " << make_tuple( err.value(), bytes_transferred, m_SendQueue.size() )); assert(false == m_Socket->GetSocket().is_open()); return; } m_SendQueue.pop_front(); if ( err ) { // ·¢ËÍʧ°Ü APP_ERROR("TCPClientSocket::HandleTcpSend error " << make_tuple( err.value(), bytes_transferred, m_SendQueue.size() )); this->GetListener()->OnSocketReceiveFailed(this, err.value()); } else { if ( m_SendQueue.empty() ) { return; } else { this->DoAsyncSend(m_SendQueue.front()); } } }
void DVBProvider::onReadSection( boost::asio::posix::stream_descriptor *io, ID pid, util::Buffer *buf, const boost::system::error_code& error, size_t transferred ) { bool tryRead=true; if (error) { if (error.value() == boost::system::errc::timed_out) { // Timeout timeout( pid ); } else if (error.value() != boost::system::errc::value_too_large) { printf( "[DVBProvider] Read section error!!!: err(%s,%d), pid=%04x, transferred=%d, capacity=%d!\n", error.message().c_str(), error.value(), pid, transferred, buf->capacity() ); tryRead=false; } } if (transferred) { buf->resize( transferred ); enqueue( pid, buf ); buf = NULL; } if (tryRead) { readSection( io, pid, buf ); } else { freeNetworkBuffer( buf ); } }
void TimeoutSerial::readCompleted(const boost::system::error_code& error, const size_t bytesTransferred) { if(!error) { result=resultSuccess; this->bytesTransferred=bytesTransferred; return; } //In case a asynchronous operation is cancelled due to a timeout, //each OS seems to have its way to react. #ifdef _WIN32 if(error.value()==995) return; //Windows spits out error 995 #elif defined(__APPLE__) if(error.value()==45) { //Bug on OS X, it might be necessary to repeat the setup //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html performReadSetup(setupParameters); return; } #else //Linux if(error.value()==125) return; //Linux outputs error 125 #endif result=resultError; }
void c_udp_wrapper_asio::read_handle(const boost::system::error_code& error, size_t bytes_transferred) { // std::cout << "udp read handle" << std::endl; // std::cout << "readed " << bytes_transferred << " bytes" << std::endl; if (error && (error.value() != 10061)) // http://stackoverflow.com/a/16763404 std::cout << error.message() << " value " << error.value() << std::endl; // assert(m_bytes_readed == 0); m_bytes_readed = bytes_transferred; m_socket.async_receive_from(boost::asio::buffer(m_buffer), m_sender_endpoint, boost::bind(&c_udp_wrapper_asio::read_handle, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); }
inline void length_framed_connection::report(boost::system::error_code ec) { switch (ec.value()) { case io::error::eof: report(std::errc::not_connected); break; default: report(static_cast<std::errc>(ec.value())); break; } }
/// dummy function, called after send void CBoostTapNetAdapt::handle_send (boost::shared_ptr<CNetworkFrame> frame, const boost::system::error_code& error, std::size_t bytes_transferred) { if (error.value() != 0) { DBG_ERROR(FMT("Error sending data (%1%): %2%") % error.value() % error.message()); } else if (bytes_transferred != frame->size) { DBG_ERROR(FMT("bytes transferred (%1%) != buffer size (%2%)!") % bytes_transferred % frame->size); } }
void OnSendComplete(const boost::system::error_code &err, CMsgBuffer::Ptr msg) { std::cout << "ErrorCode" << err.value() << std::endl; if (err.value() == boost::asio::error::not_connected) { cli.Reset(); return; } std::cout << "OnSendComplete" << std::endl; std::cout << "OnSendComplete times \"" << times++ << "\"" <<std::endl; }
void TtyStream::HandleReadSome(int reference, const boost::system::error_code& error, size_t bytes_transferred) { lua_State* L = LuaNode::GetLuaVM(); lua_rawgeti(L, LUA_REGISTRYINDEX, reference); luaL_unref(L, LUA_REGISTRYINDEX, reference); m_pending_reads--; if(!error) { LogDebug("TtyStream::HandleReadSome (%p) (id:%u) - Bytes Transferred (%lu)\n", this, m_fd, (unsigned long)bytes_transferred); lua_getfield(L, 1, "read_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); const char* data = m_inputArray.c_array(); lua_pushlstring(L, data, bytes_transferred); LuaNode::GetLuaVM().call(2, LUA_MULTRET); } else { // do nothing? if(lua_type(L, 1) == LUA_TUSERDATA) { userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1)); LogWarning("TtyStream::HandleReadSome (%p) (id:%u) - No read_callback set on %s (address: %p, possible obj: %p)", this, m_fd, luaL_typename(L, 1), ud, ud->pT); } else { LogWarning("TtyStream::HandleReadSome (%p) (id:%u) - No read_callback set on %s", this, m_fd, luaL_typename(L, 1)); } } } else { lua_getfield(L, 1, "read_callback"); if(lua_type(L, 2) == LUA_TFUNCTION) { lua_pushvalue(L, 1); LuaNode::BoostErrorCodeToLua(L, error); // -> nil, error code, error message if(error.value() != boost::asio::error::eof && error.value() != boost::asio::error::operation_aborted) { LogError("TtyStream::HandleReadSome with error (%p) (id:%u) - %s", this, m_fd, error.message().c_str()); } LuaNode::GetLuaVM().call(4, LUA_MULTRET); } else { LogError("TtyStream::HandleReadSome with error (%p) (id:%u) - %s", this, m_fd, error.message().c_str()); if(lua_type(L, 1) == LUA_TUSERDATA) { userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1)); LogWarning("TtyStream::HandleReadSome (%p) (id:%u) - No read_callback set on %s (address: %p, possible obj: %p)", this, m_fd, luaL_typename(L, 1), ud, ud->pT); } else { LogWarning("TtyStream::HandleReadSome (%p) (id:%u) - No read_callback set on %s", this, m_fd, luaL_typename(L, 1)); } } } lua_settop(L, 0); }
void TransPanel::recvSerialPortErrorCB(boost::system::error_code ec) { if(ec.value() != 995) { LOG( "%d - %s" , ec.value() , ec.message().c_str()); QString com_error; com_error.sprintf("串口读取错误:%s" ,ec.message().c_str() ); SERROR(com_error); } }
bool CheckErrorCode(boost::system::error_code& err) { // connection reset can happen when host did not start up // before the client wants to connect if (!err || err.value() == connection_reset || err.value() == resource_unavailable_try_again) { // this should only ever happen with async sockets, but testing indicates it happens anyway... return false; } else { LOG_L(L_WARNING, "Network error %i: %s", err.value(), err.message().c_str()); return true; } }
void basic_socket_impl::data_recv_handler(const boost::system::error_code& ec, size_t bytes_transferred, bool ischeck) { if (!isworking()) return; if (ec.value() == 0) { recv_helper_.reading_buffer_.use_buffer(bytes_transferred); int ret = on_data_recv(bytes_transferred); if (ret == 0) { if (recv_helper_.reading_buffer_.buffer_left() < 128) { recv_helper_.reading_buffer_.remove_used(); } //如果不是超时回调,则重置接收状态 if (!ischeck) { recv_helper_.is_recving_ = false; } //如果缓冲有空闲,并且没有在接收状态 if (recv_helper_.reading_buffer_.buffer_left() > 0 && !recv_helper_.is_recving_) { recv_helper_.is_recving_ = true; s.async_receive( boost::asio::buffer(recv_helper_.reading_buffer_.buffer(), recv_helper_.reading_buffer_.buffer_left()), boost::bind(&basic_socket_impl::data_recv_handler, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, false)); } else if (recv_helper_.reading_buffer_.buffer_left() == 0) { if (option("close_on_rdbuffer_full") == "1") { last_socket_error_ = 10055; close(true); } else { recv_helper_.is_recving_ = false; //缓冲区满了,10ms后再读数据,让目前的数据有时间处理 check_data_recv_.expires_from_now(boost::posix_time::millisec(1)); check_data_recv_.async_wait( boost::bind(&basic_socket_impl::on_recv_check, this->shared_from_this(), boost::asio::placeholders::error)); } } } } else { if (work_state != work_state_closed) { last_socket_error_ = ec.value(); close(true); } } }
void CNetwork::OnWrite(const boost::system::error_code &error_code) { boost::lock_guard<boost::mutex> lock_guard(m_CmdWriteBufferQueueMutex); #ifdef _DEBUG logprintf("<<<< %s", m_CmdWriteBufferQueue.front().c_str()); #endif m_CmdWriteBufferQueue.pop(); if (error_code.value() != 0) { CCallbackHandler::Get()->ForwardError( EErrorType::CONNECTION_ERROR, error_code.value(), fmt::format("error while writing: {}", error_code.message())); } }
void onResolveSuccess(const boost::system::error_code& error, BoostResolver::iterator remoteEndpoint, const shared_ptr<Resolver>& self) { m_scheduler.cancelEvent(m_resolveTimeout); if (error) { if (error == boost::system::errc::operation_canceled) { return; } return m_onError("Remote endpoint hostname or port cannot be resolved: " + error.category().message(error.value())); } BoostResolver::iterator end; for (; remoteEndpoint != end; ++remoteEndpoint) { IpAddress address(EndPoint(*remoteEndpoint).address()); if (m_addressSelector(address)) { return m_onSuccess(address); } } m_onError("No endpoint matching the specified address selector found"); }
void onResolveSuccess(const boost::system::error_code& error, typename resolver::iterator remoteEndpoint, const shared_ptr<Resolver>& self) { scheduler::cancel(m_resolveTimeout); if (error) { if (error == boost::system::errc::operation_canceled) return; return m_onError("Remote endpoint hostname or port cannot be resolved: " + error.category().message(error.value())); } typename resolver::iterator end; for (; remoteEndpoint != end; ++remoteEndpoint) { if (m_addressSelector(typename Protocol::endpoint(*remoteEndpoint).address())) return m_onSuccess(*remoteEndpoint); } m_onError("No endpoint matching the specified address selector found"); }
//----------------------------------------------------------------------------- void ScanDataReceiver::handleSocketRead(const boost::system::error_code& error) { if (!error ) { // Read all received data and write it to the internal ring buffer instream_.clear(); while(!instream_.eof()) { char buf[4096]; instream_.read(buf,4096); int bytes_read = instream_.gcount(); writeBufferBack(buf,bytes_read); } // Handle (read and parse) packets stored in the internal ring buffer while( handleNextPacket() ) {} // Read data asynchronously boost::asio::async_read(*tcp_socket_, inbuf_, boost::bind(&ScanDataReceiver::handleSocketRead, this, boost::asio::placeholders::error)); } else { if( error.value() != 995 ) std::cerr << "ERROR: " << "data connection error: " << error.message() << "(" << error.value() << ")" << std::endl; disconnect(); } last_data_time_ = std::time(0); }
void LogFileDescriptorToLog::handle_log_line(const char * logname, Logger::LogLevel log_level, boost::asio::posix::stream_descriptor &sd, boost::asio::streambuf & buf, boost::system::error_code ec, size_t bytes_read) { if (ec) { if (ec == boost::asio::error::eof) { // stop logging return; } else { logger_->log_error(logname, "Failed to read log line %i (%s), continuing", ec.value(), ec.message().c_str()); } } else { std::string line; std::istream in_stream(&buf); std::getline(in_stream, line); logger_->log(log_level, logname, "%s", line.c_str()); } start_log(logname, log_level, sd, buf); }
void TcpConnection::_handleRead(const boost::system::error_code &ec, std::size_t len) { switch(ec.value()) { case boost::asio::error::operation_aborted: case boost::system::errc::no_such_file_or_directory: break; case boost::system::errc::success: { auto bufs = _buf.data(); std::string line( boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + len ); _buf.consume(len); std::cout<<__FUNCTION__<<": "<<line<<std::endl; _recvMsg(line); } default: boost::asio::async_read_until(_sock, _buf, "\n", boost::bind(&TcpConnection::_handleRead, this, boost::placeholders::_1, boost::placeholders::_2 ) ); break; } }
void stratum_client::handle_connect(const boost::system::error_code& err) { if (!inited_) return; if (!err) { { std::cout << "Try to login..." << std::endl; std::ostream request_stream(&request_); request_stream << "{\"id\": 1, \"method\": \"login\", " "\"params\": { " "\"login\":\"" << login_ << "\"," "\"pass\" : \"" << pwd_ << "\", " "\"agent\" : \"embedded_miner/1.0\"" "}" "}\n"; } boost::asio::async_write(socket_, request_, boost::bind(&stratum_client::handle_write_completed, this, boost::asio::placeholders::error)); } else { ec_(err.value(), err.message(), this); } }
void o3d3xx::PCICClient::WriteHandler(State state, const boost::system::error_code& ec, std::size_t bytes_transferred, const std::string& out_content_buffer, std::size_t bytes_remaining) { if(ec) { throw o3d3xx::error_t(ec.value()); } if(bytes_remaining - bytes_transferred > 0) { this->DoWrite(state, out_content_buffer, bytes_remaining - bytes_transferred); } else { switch(state) { case State::PRE_CONTENT: this->DoWrite(State::CONTENT, out_content_buffer); break; case State::CONTENT: this->DoWrite(State::POST_CONTENT, out_content_buffer); break; case State::POST_CONTENT: std::unique_lock<std::mutex> lock(this->out_mutex_); this->out_completed_.store(true); this->out_cv_.notify_all(); break; } } }
void TcpShapeClient::handle_read(const boost::system::error_code& error) { if (!error) { std::string msg; std::istream is(&buffer); std::getline(is, msg); if(msg.empty()) return; // create signal to notify listeners sMessage(msg); read(); } else { // try to reconnect if external host disconnects if(error.value() != 0) { isConnected = false; sDisconnected(endPoint); // schedule a timer to reconnect after 5 seconds reconnectTimer.expires_from_now(boost::posix_time::seconds(5)); reconnectTimer.async_wait(boost::bind(&TcpShapeClient::do_reconnect, this, boost::asio::placeholders::error)); } else do_close(); } }
void basic_socket_impl::on_data_sended_notify(const boost::system::error_code& ec, size_t byte_transfered) { if (ec.value() != 0) { send_helper_.is_sending_ = false; } else { send_helper_.sending_buffer_.use_data(byte_transfered); if (send_helper_.sending_buffer_.is_complete()) { if (!send_new_buffer()) { if (close_when_idle_) { ios_.post(boost::bind(&basic_socket_impl::close, this->shared_from_this(), false)); } send_helper_.is_sending_ = false; } } //没发完,继续发剩下的 else { s.async_send(boost::asio::buffer(send_helper_.sending_buffer_.data(), send_helper_.sending_buffer_.data_left()), boost::bind(&basic_socket_impl::on_data_sended_notify, this->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } }
//http包体的读取回调函数 void CHttpClient::handle_ContentRead(boost::system::error_code err,size_t bytes_transfarred) { if(!err||err.value()==2) { std::istream response_stream(&respone_); response_stream.unsetf(std::ios_base::skipws);//asio::streambuf 转换成istream 并且忽略空格 nContentLen=respone_.size(); //将数据流追加到header里 char *cont=new char[nContentLen+1]; //此处申请了内存,注意释放。 memset(cont+nContentLen,0,1); response_stream.read(cont,nContentLen); this->m_respone->errorCode=0; this->m_respone->msg=boost::shared_array<char>(cont); this->m_respone->len=this->nContentLen; mHttpBack(this->m_respone); }else { this->m_respone->errorCode=7; this->m_respone->errMsg="内容读取错误"; mHttpBack(this->m_respone); } }
void AsyncSerial::readEnd(const boost::system::error_code& error, size_t bytes_transferred) { if (error) { #ifdef __APPLE__ if (error.value()==45) { //Bug on OS X, it might be necessary to repeat the setup //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html doRead(); return; } #endif //__APPLE__ //error can be true even because the serial port was closed. //In this case it is not a real error, so ignore if (isOpen()) { doClose(); setErrorStatus(true); } } else { if (pimpl->callback) pimpl->callback(pimpl->readBuffer, bytes_transferred); doRead(); } }
void TCPConnection::AsyncWriteCompleted(const boost::system::error_code& error, size_t bytes_transferred) { UpdateAutoLogoutTimer(); if (error.value() != 0) { if (connection_state_ != StateConnected) { // The write failed, but we've already started the disconnection. So we should not log the failure // or enqueue a new disconnect. return; } String message; message.Format(_T("The write operation failed. Bytes transferred: %d"), bytes_transferred); ReportDebugMessage(message, error); EnqueueDisconnect(); } else { bool containsQueuedSendOperations = operation_queue_.ContainsQueuedSendOperation(); if (!containsQueuedSendOperations) { OnDataSent(); } } operation_queue_.Pop(IOOperation::BCTWrite); ProcessOperationQueue_(0); }
void handleRead(const boost::system::error_code &ec) { if (ec) { static_cast<T*>(this)->on_mq_read_error(ec.value()); return; } constexpr int MAXBUFLEN = 1024; char buf[MAXBUFLEN]; unsigned int prio = 0; int res = mq_receive(mqid, buf, MAXBUFLEN, &prio); if (res > 0) { std::vector<uint8_t> data(buf, buf + res); static_cast<T*>(this)->on_mq_data(data, prio); } else { static_cast<T*>(this)->on_mq_read_error(errno); } streamDescriptor.async_read_some( boost::asio::null_buffers(), boost::bind(&MessageQueue::handleRead, this, boost::asio::placeholders::error)); }
bool equivalent (boost::system::error_code const& error, int ev) const noexcept override { return error.value() == ev && &error.category() == this; }
void csasServer::read_handler(const boost::system::error_code& error, std::size_t bytes_transferred, char* msg, tcp::socket* socket) { cout<<"Принято: "<<(error.value()==0?"":error.message())<<" "<<msg<<" Принято байт: "<<bytes_transferred<<endl; delete msg; // отсюда запускаем передачу данных boost::asio::async_write(*socket,boost::asio::buffer("Наш ответ Чемберлену"),boost::bind(&csasServer::write_handler, this,boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred,socket)); }