Wednesday, April 30, 2008

Asio实现线程池绑定多个socket对外部进行响应

主要用到几个基本的步骤
1,你要让很多个socket绑定在多个端口上
service.sin_family = AF_INET;
service.sin_addr.s_addr = htonl(INADDR_ANY);
for (int i = 0; i< svnodes_num;) {
g_bindsocks[i] = socket( AF_INET, SOCK_DGRAM, 0);
if ((g_bindsocks[i]) < 0)
return false;
service.sin_port = htons(nextport);
if (bind(g_bindsocks[i], (sockaddr*) &service, sizeof(service))>=0) {
fcntl(g_bindsocks[i], F_SETOWN, getpid());
ioctl(g_bindsocks[i], FIOASYNC, &on);
ioctl(g_bindsocks[i], FIONBIO, &on);
g_bindsocks_ports[i] = nextport;
i ++;
} else {
close(g_bindsocks[i]);
}
nextport++;
if (nextport >=0x10000)
return false;
}
2,你要忽略所有的sigio信号同时跑起asio的udp多线程的server端
void* dg_echo(void* param)
{
signal(SIGIO, SIG_IGN); //忽略所有的sigio信号
AsioFrame(); //Use the asioframe to handle this
}
3,udp_server的代码在asio的tutorial里面
我现在把怎样绑定写出来
void AsioFrame() {
try
{
#ifdef DEBUG
std::cout<<"asioframe run!"< #endif
boost::asio::io_service io_service;
uint32 numsocks = Util::GetNumOfVirtualNodes();
int* sockptr = (int *)Util::GetBindSocksPtr();
udp_server* serverpool[100];
if (numsocks> 100)
numsocks = 100;
for (uint32 id = 0; id < numsocks; id ++)
{
serverpool[id] = new udp_server(io_service, id, sockptr[id]);
}
io_service.run();

/*for (uint32 id = 0; id < numsocks; id ++)
{
delete serverpool[id];
}*/
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}

eclipse链接boost库的情况

最近在做一个项目在linux用到boost的库,以下是我遇到的一些问题和解决方案
最新出的boost 1.35库里面已经包含了asio的库了!
大家都知道boost和asio的库都是头文件的库(不用编译),但是新版本的boost里面,
最起码有一个库是必须编译的 即Boost.System,如果在编译的时候不添加这个库的话,
用到asio的时候(或者其他,我没试过),就会报一个undefined bind::system::get_system_proxy()等等错误。处理方法是在编译的时候加入libboost_system_gc41_mt.so

这个库编译方法有两种:
1,在boost1.35目录下面
#./configure
#make install
这样会把所有的库添加到你的/usr/local/lib下面
然后,你试一下還是不行,这是因为你还没有装在到cash里面,接下来要这么处理
#sudo gedit /etc/ld.so.conf (里面可能包含了其他的conf文件) 里面是动态库的地址
一般来说,地址应该已经在里面了
#sudo ldconfig 重新刷一边cash
2,第二个方法不用全部编译,先
#./configure
然后在boost_1_35_0/tools/jam/src/bin.linuxx86 把bjam考到
boost_1_35_0/libs/system/build下
然后到该目录下#sudo bjam
libboost_system_gc41_mt.so会产生在boost1_35的根目录的bin.v2里面
其他操作和方法一一样

还有一个注意是,动态库和静态库一样需要在linker里面写上

boost_1_35_0/libs/system/build