的處理程序我寫我叫asyncAccept自己的函數來封裝標準的boost ::支持ASIO ::知識產權::受體:: async_accept,但是當我跑我的程序中發生的問題。 發生錯誤,並輸出「參數無效」。看起來表達有錯誤:使用async_accept
boost::bind(handle_accept, placeholders::error, socket, tcp_version, port_num, handler));
我想知道是什麼問題。 完整代碼如下。我的母語不是英語,請耐心等待一下~~ 非常感謝!
----------------------------------------asyncAccept.cpp-------------------------------
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "impl/asyncAccept.h"
using namespace boost::asio;
namespace asyncTcp{
error_type illegal_version = -1;
error_type accept_error = -2;
const int TCPV4 = 4;
const int TCPV6 = 6;
io_service io_server;
ip::tcp::acceptor _acceptor(io_server);
ip::tcp::socket _socket(io_server);
void *servSocket = &_socket;
void handle_accept(const boost::system::error_code& error, void* socketPtr, const int tcp_version, unsigned short port_num, callback handler);
void init_acceptor(const int tcp_version, unsigned short port_num);
//bind a socket with a port
void asyncAccept(void* socketPtr, const int tcp_version, unsigned short port_num, callback handler){
if (tcp_version != TCPV4 && tcp_version != TCPV6)
throw illegal_version;
init_acceptor(tcp_version, port_num);
ip::tcp::socket *socket = reinterpret_cast<ip::tcp::socket*>(socketPtr);
_acceptor.async_accept((*socket),
boost::bind(handle_accept, placeholders::error, socket, tcp_version, port_num, handler));
return;
}
void handle_accept(const boost::system::error_code& error, void* socketPtr, const int tcp_version, unsigned short port_num, callback handler){
if (!error){
//cycle server
handler();
asyncAccept(socketPtr, tcp_version, port_num, handler);
}
else
throw boost::system::system_error(error);
}
void init_acceptor(const int tcp_version, unsigned short port_num){
if (TCPV4 == tcp_version){
ip::tcp::endpoint ep(ip::tcp::v4(), port_num);
_acceptor.open(ip::tcp::v4());
_acceptor.bind(ep);
}
else{
ip::tcp::endpoint ep(ip::tcp::v6(), port_num);
_acceptor.open(ip::tcp::v6());
_acceptor.bind(ep);
}
}
void run_server(){
io_server.run();
return;
}
}//namespace
-----------------------------------impl/asyncAccept.h----------------------------------
#ifndef SERV_SOCKET_H
#define SERV_SOCKET_H
namespace asyncTcp{
#ifndef CALL_BACK
#define CALL_BACK
typedef void (*callback)();
#endif
#ifndef ERROR_TYPE
#define ERROR_TYPE
typedef int error_type;
#endif
extern error_type illegal_version;
extern error_type accept_error;
//extern void* io_server;
extern void* servSocket;
extern const int TCPV4;
extern const int TCPV6;
void asyncAccept(void* socketPtr, const int tcp_version, unsigned short port_num, callback handler);
void run_server();
}
#endif /* SERV_SOCKET_H */
爲什麼你傳遞指針對象作爲'無效*'然後'reinterpret_cast'呢?這是一種糟糕的風格。 – 2013-05-13 18:02:49
@herbert:我的答案是否適合你? – Simon 2013-05-14 11:11:51
@Simon:是的,非常感謝! – herbert 2013-05-14 12:03:10