acl 中的半驻留线程池服务器例子.

来源:互联网 发布:一致性hash算法原理 编辑:程序博客网 时间:2024/06/05 21:50

server:


        // 半驻留式线程池.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"


#include <acl\lib_acl.h>


#pragma comment(lib,"lib_acl.lib")


void client_thread(void* arg)
{
ACL_VSTREAM* client = (ACL_VSTREAM*)arg;
char buffer[1024] = { 0 };
int n = 0;
ACL_VSTREAM_SET_RWTIMO(client, 30);
while (1)
{
// 等待客户端发来的数据
n = acl_vstream_read(client, buffer, sizeof(buffer));
if (n == ACL_VSTREAM_EOF)
break;
printf("来自于客户端的消息:%s\n", buffer);
if (acl_vstream_writen(client, buffer, n) == ACL_VSTREAM_EOF)
break;


}
// 关闭客户端流
acl_vstream_close(client);
}
int _tmain(int argc, _TCHAR* argv[])
{


acl_lib_init();

// 半驻留式线程池.
acl_pthread_pool_t* pool = NULL;
acl_pthread_pool_attr_t attr;
acl_pthread_pool_attr_init(&attr);
acl_pthread_pool_attr_set_idle_timeout(&attr, 10);
acl_pthread_pool_attr_set_threads_limit(&attr, 100);
    pool = acl_pthread_pool_create(&attr);
char buferror[1024] = { 0 };
ACL_VSTREAM* listenStream =  acl_vstream_listen("127.0.0.1:5050", 500);
if (listenStream == NULL)
{
printf("%s\n", acl_last_strerror(buferror, 1023));
system("pause");
return 0;
}
ACL_VSTREAM* client = NULL;
char bufferIp[1024] = { 0 };


while (true)
{
memset(bufferIp, 0, 1024);
client = acl_vstream_accept(listenStream, bufferIp, 1023);
if (client == NULL)
{
printf("接受连接出现了错误,准备退出...:%s\n", acl_last_strerror(buferror, 1023));
break;
}
printf("接受了一个连接,该ip是:%s\n", bufferIp);
acl_pthread_pool_add(pool, client_thread, client);
}
acl_pthread_pool_destroy(pool);


acl_lib_end();
system("pause");
return 0;
}


client:


  #include <acl\lib_acl.h>
#pragma comment(lib,"lib_acl.lib")
int main(int argc, char* argv[])
{
acl_lib_init();
printf("准备连接服务器....\n");
ACL_VSTREAM* client = acl_vstream_connect("127.0.0.1:5050", ACL_NON_BLOCKING, 30, 30, 4096);
printf("连接就绪.....\n");
char buff[4096] = "hello, my name is ysd";
char buffer[1024] = { 0 };
while (true)
{  
if (acl_vstream_writen(client, buff, strlen(buff)) == ACL_VSTREAM_EOF)
break;
memset(buffer, 0, 1024);
if (acl_vstream_read(client, buffer, 1023) == ACL_VSTREAM_EOF)
break;
printf("%s\n", buffer);
}


acl_lib_end();
system("pause");
return 0;
}

         

0 0
原创粉丝点击