我写了这个:
#include <vector>
#include <iostream>
#include <sstream>
#include <boost/asio.hpp>
#include <tr1/memory>
#include <boost/bind.hpp>
#include <stdint.h>
using namespace boost::asio;
using namespace boost::asio::ip;
class tcpServer{
public:
class connection{
tcp::socket socketConnection;
enum {CONNECTED, CLOSED, CREATED}STATUS;
public:
uint32_t addr;
uint16_t port;
connection(boost::asio::io_service &ioServ): socketConnection(ioServ){
STATUS = CREATED;
}
void setConnected(bool is) {
if (is) {
STATUS = CONNECTED;
port = socketConnection.remote_endpoint().port();
addr
= socketConnection.remote_endpoint().address().to_v4().to_ulong();
std::cout << "Connected to "
<< socketConnection.remote_endpoint().address().to_v4().to_string()
<< " : " << socketConnection.remote_endpoint().port()
<< "\n";
}
}
tcp::socket& getSocket(){
return socketConnection;
}
};
typedef std::tr1::shared_ptr<tcpServer::connection> CONNSHPTR;
private:
boost::asio::io_service io_service;
tcp::acceptor tcpAcceptor;
int localPort;
void accept(CONNSHPTR connection, const boost::system::error_code& error){
connection->setConnected(true);
std::cout.flush();
}
void startAccept(){
CONNSHPTR newConn(new connection(tcpAcceptor.io_service()));
tcpAcceptor.async_accept(newConn->getSocket(), boost::bind(
&tcpServer::accept, this, newConn,
boost::asio::placeholders::error));
}
public:
tcpServer(int localPort) :
io_service(), tcpAcceptor(io_service, tcp::endpoint(tcp::v4(),
localPort)) {
this->localPort = localPort;
}
void start(){
io_service.run();
startAccept();
}
};
int main(int argc, char** argv) {
try{
tcpServer tp(1033);
tp.start();
}catch(std::exception &e){
std::cout << e.what();
}
sleep(5000);
return 0;
}
然后我去了终端,我写了telnet localhost 1033.Telnet说我已连接,但处理程序没有被调用(gdb没有命中断点,coutS没有效果)。如果我杀了程序,telnet会说连接已经关闭。所以似乎建立了连接,但为什么处理程序不会被调用?
编辑:
奇怪的是,如果在start()中我将ioservice.run()放在 startAccept()之后。现在我想知道为什么这样有效...事实上后来我再次调用start accept它仍然有效,它是在ioservice.run()调用之后....
答案 0 :(得分:5)
来自asio docs:
run()函数阻塞,直到所有工作完成,并且不再有调度程序,或者直到io_service已停止。
当run()在 startAccept()之前被调用时,它会立即返回,因为它还没有任何关系。然后调用startAccept(),它将套接字置于接受模式(因此,当您在服务器上telnet时,网络子系统接受它),但之后不调用run(),因此永远不会调用您的接受处理程序。 p>