static int StartTcpServer(const char* ip, int port) { socket_t sock = tcpserver_create(ip, port, 256); if(0 == sock) { printf("server listen at %s.%d error: %d\n", ip?ip:"127.0.0.1", port, socket_geterror()); return -1; } printf("server listen at %s:%d\n", ip?ip:"localhost", port); s_tcp = aio_socket_create(sock, 1); return aio_socket_accept(s_tcp, OnAccept, NULL); // start server }
static int StartUdpServer(const char* ip, int port) { socket_t sock = udpserver_create(ip, port); if(0 == sock) { printf("udp-server bind at %s.%d error: %d\n", ip?ip:"127.0.0.1", port, socket_geterror()); return -1; } s_udp = aio_socket_create(sock, 1); //aio_socket_recvfrom(s_udp, s_rxbuffer, sizeof(s_rxbuffer)-1, OnUdpRecv, NULL); return 0; }
int main(int argc, char* argv[]) { char c; int cpu = system_getcpucount(); socket_t server; aio_socket_t aioserver; memset(s_buffer, 'A', sizeof(s_buffer)-1); aio_socket_init(cpu); s_thpool = thread_pool_create(cpu, cpu, cpu*2); while(cpu > 0) { thread_pool_push(s_thpool, AIOWorker, NULL); --cpu; } server = Listen(50000); aioserver = aio_socket_create(server, 1); aio_socket_accept(aioserver, OnAccept, aioserver); printf("server listen at: %d\n", 50000); for(c = getchar(); 'q' != c; c = getchar()) { switch(c) { case 'c': // close socket aio_socket_destroy(aioserver); break; default: printf("unknown command.\nc : close socket\n"); } } aio_socket_destroy(aioserver); thread_pool_destroy(s_thpool); aio_socket_clean(); return 0; }
static void OnAccept(void* param, int code, socket_t socket, const char* ip, int port) { void* ptr; aio_socket_t aio; aio_socket_t server = (aio_socket_t)param; printf("OnAccept ==> %d; %s:%d\n", code, ip, port); if(0 != code) return; ptr = malloc(1024+sizeof(aio)); aio = aio_socket_create(socket, 1); *(aio_socket_t*)ptr = aio; memset((aio_socket_t*)ptr+1, 0, 1024); aio_socket_recv(aio, (aio_socket_t*)ptr+1, 1023, OnRead, ptr); // continue accept aio_socket_accept(server, OnAccept, server); }