void netserver_tick(NetServer *s) { int i; int n; if(!s) return; if(s->listen_sock != INVALID_SOCKET) { SOCKET as; struct sockaddr client_address = {0}; while((as = socket_accept(&s->listen_sock, &client_address)) != INVALID_SOCKET) { NetLink *l = NetLink_Create(s->ctxt); SOCK_CLEAR_DELAY(as); sock_set_noblocking(as); l->sock = as; l->address = client_address; l->s = s; *alnk_push(&s->clients) = l; } } n = alnk_size(&s->clients); for( i = n - 1; i >= 0; --i ) { NetLink *c = s->clients[i]; if(!netlink_tick(c)) { NetLink_Destroy(&c); alnk_rm(&s->clients,i,1); } } }
LPDESC DESC_MANAGER::AcceptP2PDesc(LPFDWATCH fdw, socket_t bind_fd) { socket_t fd; struct sockaddr_in peer; char host[MAX_HOST_LENGTH + 1]; if ((fd = socket_accept(bind_fd, &peer)) == -1) return NULL; strlcpy(host, inet_ntoa(peer.sin_addr), sizeof(host)); LPDESC_P2P pkDesc = M2_NEW DESC_P2P; if (!pkDesc->Setup(fdw, fd, host, peer.sin_port)) { sys_err("DESC_MANAGER::AcceptP2PDesc : Setup failed"); socket_close(fd); M2_DELETE(pkDesc); return NULL; } m_set_pkDesc.insert(pkDesc); ++m_iSocketsConnected; sys_log(0, "DESC_MANAGER::AcceptP2PDesc %s:%u", host, peer.sin_port); P2P_MANAGER::instance().RegisterAcceptor(pkDesc); return (pkDesc); }
void socket_server( int server ) { pthread_t tid; pthread_attr_t attr; socket_client_t *client; // Setup client serving threads to be detached pthread_attr_init( &attr ); pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); while( 1 ) { // Allocate new space for the client information client = (socket_client_t*)malloc( sizeof(socket_client_t) ); if( client == NULL ) { perror( "could not allocate space for client" ); exit( 1 ); } // Get a new client connection client->sock = socket_accept( server, &client->addr ); // Spawn a worker to serve the client pthread_create( &tid, &attr, socket_client, (void*)client ); } }
void start_multiprocess_server(socketfd_t listen_socket, OneConnectionService service_function){ /* wait at receive SIGCHLD, release child resource for multiprocess && concurrent server */ signal(SIGCHLD, sigchid_waitfor_child); while(1){ socketfd_t client_socket; SocketAddr client_addr; client_socket = socket_accept(listen_socket, client_addr); if( client_socket < 0 ){ perror("accept error"); continue; } int child_pid = fork(); if( child_pid == 0 ){ int ret = close(listen_socket); if( ret < 0 ) perror("close listen_socket error"); service_function(client_socket, client_addr); ret = close(client_socket); if( ret < 0 ) perror("close client_socket error"); exit(EXIT_SUCCESS); } else if( child_pid > 0 ){ close(client_socket); } else { perror("fork error"); } } }
static int test_server(struct harness_t *harness_p) { struct ssl_context_t context; struct ssl_socket_t ssl_socket; struct socket_t listener, socket; struct inet_addr_t addr; char buf[8]; /* Create a context with default settings. */ BTASSERT(ssl_context_init(&context) == 0); /* Create a socket and connect to the server. */ BTASSERT(socket_open_tcp(&listener) == 0); BTASSERT(socket_listen(&listener, 5) == 0); BTASSERT(socket_accept(&listener, &socket, &addr) == 0); /* Wrap the socket in SSL. */ BTASSERT(ssl_socket_init(&ssl_socket, &context, &socket, ssl_socket_mode_server_t) == 0); BTASSERT(ssl_socket_handshake(&ssl_socket) == 0); /* Transfer data to and from the server. */ BTASSERT(ssl_socket_read(&ssl_socket, &buf[0], 6) == 6); BTASSERT(strcmp("hello", buf) == 0); BTASSERT(ssl_socket_write(&ssl_socket, "goodbye", 8) == 8); /* Close the connection. */ BTASSERT(socket_close(&socket) == 0); return (0); }
void knet_channel_ref_update_accept(kchannel_ref_t* channel_ref) { kchannel_ref_t* client_ref = 0; kloop_t* loop = 0; socket_t client_fd = 0; verify(channel_ref); /* 查看选取器是否有自定义实现 */ client_fd = knet_impl_channel_accept(channel_ref); if (!client_fd) { /* 默认实现 */ client_fd = socket_accept(knet_channel_get_socket_fd(channel_ref->ref_info->channel)); } verify(client_fd > 0); knet_channel_ref_set_state(channel_ref, channel_state_accept); knet_channel_ref_set_event(channel_ref, channel_event_recv); if (client_fd) { loop = knet_channel_ref_choose_loop(channel_ref); if (loop) { client_ref = knet_channel_ref_accept_from_socket_fd(channel_ref, loop, client_fd, 0); verify(client_ref); knet_channel_ref_set_user_data(client_ref, channel_ref->ref_info->user_data); /* 设置回调 */ knet_channel_ref_set_cb(client_ref, channel_ref->ref_info->cb); /* 添加到其他loop */ knet_loop_notify_accept(loop, client_ref); } else { client_ref = knet_channel_ref_accept_from_socket_fd(channel_ref, channel_ref->ref_info->loop, client_fd, 1); verify(client_ref); knet_channel_ref_set_user_data(client_ref, channel_ref->ref_info->user_data); /* 调用回调 */ if (channel_ref->ref_info->cb) { channel_ref->ref_info->cb(client_ref, channel_cb_event_accept); } } } }
int main(int arg, char *args[]) { sql_connect(&mysql, &conn); //如果没有参数,main函数返回 if(arg < 2) { printf("usage:myserver port\n"); return EXIT_FAILURE; } //setdaemon(); //将第一个参数转化为整数 int iport = atoi(args[1]); if(iport == 0) { printf("port %d is invalid\n", iport); return EXIT_FAILURE; } int st = socket_create(iport); socket_accept(st); sql_disconnect(conn); close(st); printf("myhttp is end\n"); return 0; }
bool socket_server_serve (socket_t *server, socket_t *client, socket_client_handler_t handler) { char *buffer; bool handled; if (!socket_accept (server, client)) { return true; } buffer = (char *) malloc (sizeof (char) * 1024); if (!socket_receive (client, buffer, 1024)) { (void) socket_close (client); free (buffer); return true; } if (!socket_close (client)) { free (buffer); return true; } handled = handler ? handler (buffer) : socket_default_client_handler (buffer); free (buffer); return handled; }
void init_socket_example(int port, uint8_t *ip) { int i = 0; int socket = socket_open(TCP_STREAM); struct sock_addr addr; addr.port = port; addr.ip = 0; for(i=0; i<4; i++) { addr.ip |= ip[i] << i*8; } char buffer[11]; // printf("ip is %x\n", addr.ip); socket_bind(socket, &addr); socket_listen(socket, 5); struct sock_addr client; // printf("Waiting for accept\n"); logger(SOCKET, NORMAL, "waiting on accept\n"); int new_socket = socket_accept(socket, &client); logger(SOCKET, NORMAL, "coming off accept\n"); socket_send(new_socket, "Hello World", 12); printf("waiting on socket read\n"); socket_read(new_socket, buffer, 10); printf("received from socket %s\n", buffer); socket_close(new_socket); // printf("accepted the connection\n"); }
int main(void) { socket_t listener; socket_set_t clients; if(false == socket_create_socket(&listener, LIBNET_PROTOCOL_TCP, LIBNET_IPV4)) { printf("server: failed to create socket\r\n"); return -1; } socket_create_set(&clients); if(false == socket_listen(&listener, PORT)) { printf("server: failed to listen at %d\r\n", PORT); return -1; } printf("server: listening at %d..\n", PORT); while(socket_set_get_client_amount(&clients) < 1) { socket_accept(&listener, &clients); } printf("server: client connected (ip: %s)\r\n", "127.0.0.1"); _sleep(2); // to make sure the client recognizes everything socket_release_set(&clients); socket_disconnect(&listener); socket_release_socket(&listener); return 0; }
void init_socket_example(int port, uint8_t *ip) { int i = 0; int socket = socket_open(TCP_STREAM); struct sock_addr addr; addr.port = port; addr.ip = 0; for(i=0; i<4; i++) { addr.ip |= ip[i] << i*8; } // printf("ip is %x\n", addr.ip); #if 1 socket_bind(socket, &addr); socket_listen(socket, 5); struct sock_addr client; // printf("Waiting for accept\n"); logger(LOG_SOCKET, NORMAL, "waiting on accept\n"); pthread_t thread_id = 0; while(1) { int *socket_child = malloc(sizeof(int)); *socket_child = socket_accept(socket, &client); pthread_create(&thread_id, NULL, DoWork, socket_child); } #endif // printf("accepted the connection\n"); }
int main(int argc,char* argv[]) { signal(17,signal_handle); int sfd_listen=socket_init(); int sfd_client; struct sockaddr_in client_addr; char buf_client_addr[16]=""; int client_port; while(1) { memset(&client_addr,0,sizeof(struct sockaddr)); sfd_client=socket_accept(sfd_listen,(struct sockaddr*)&client_addr); if(fork()==0) { close(sfd_listen); strcpy(buf_client_addr,inet_ntoa(client_addr.sin_addr)); client_port=ntohs(client_addr.sin_port); printf("client %s:%d connect!\n",buf_client_addr,client_port); child_main(sfd_client); printf("client %s:%d disconnect!\n",buf_client_addr,client_port); close(sfd_client); exit(0); } close(sfd_client); } return 0; }
static void accept_ready(socket_t *socket, UNUSED_ATTR void *context) { assert(socket != NULL); assert(socket == listen_socket); socket = socket_accept(socket); if (!socket) return; client_t *client = (client_t *)osi_calloc(sizeof(client_t)); if (!client) { LOG_ERROR(LOG_TAG, "%s unable to allocate memory for client.", __func__); socket_free(socket); return; } client->socket = socket; if (!list_append(clients, client)) { LOG_ERROR(LOG_TAG, "%s unable to add client to list.", __func__); client_free(client); return; } socket_register(socket, thread_get_reactor(thread), client, read_ready, NULL); }
void My_epoll::handle_query() { struct epoll_event events[EPOLLSIZE]; int epollfd=epoll_create(EPOLLSIZE); if(epollfd==-1) { m_log.error("epoll create failed"); } socket_init(); set_nonblock(server_sock); QUERY_HANDLE::Query_handle handle(m_conf,&m_log); epoll_add(epollfd,server_sock,EPOLLIN|EPOLLET); std::cout<<"server wait for connecting......."<<std::endl; m_log.notice("server wait for connecting........."); while(1) { int ret=epoll_wait(epollfd,events,EPOLLSIZE,-1); for(int index=0;index<ret;index++) { if(events[index].data.fd==server_sock) { int fd_client=socket_accept(); set_nonblock(fd_client); handle(fd_client); } } } }
bool CPeerBase::Accept(socket_t fd_accept) { struct sockaddr_in peer; if ((m_fd = socket_accept(fd_accept, &peer)) == INVALID_SOCKET) { Destroy(); return false; } //socket_block(m_fd); socket_sndbuf(m_fd, 233016); socket_rcvbuf(m_fd, 233016); strlcpymt(m_host, inet_ntoa(peer.sin_addr), sizeof(m_host)); m_outBuffer = buffer_new(DEFAULT_PACKET_BUFFER_SIZE); m_inBuffer = buffer_new(MAX_INPUT_LEN); if (!m_outBuffer || !m_inBuffer) { Destroy(); return false; } fdwatch_add_fd(m_fdWatcher, m_fd, this, FDW_READ, false); OnAccept(); sys_log(0, "ACCEPT FROM %s", inet_ntoa(peer.sin_addr)); return true; }
int test_tcp() { int fd = socket_new(SOCK_STREAM); fd =socket_bind(fd, "", 9000); fd = socket_listen(fd); printf("socket fd: %d\n", fd); char cip[16] = {0}; int connfd = socket_accept(fd, cip); if (connfd < 0) { printf("accept failed\n"); return -1; } printf("start to recv\n"); char* msg = (char*)socket_recv(connfd); printf("body=%s\n", msg); socket_send(connfd, "back from server", strlen("back from server")); free(msg); close(connfd); close(fd); return 0; }
int main() { lib_init(); socket_t * server = socket_new(); int port = 5001; if(-1 == socket_bind(server, port)) { printf("port %i is busy\n", port); exit(1); } socket_listen(server); char buf[10000]; socket_t * client = NULL; while(1) { client = socket_accept(server); socket_read(client, buf, sizeof(buf)); printf("%s",buf); if (strlen(buf) != 0){ http_request_t rs; rs = http_request_parse(buf); if (strcmp(rs.method,"GET") == 0 && strcmp(rs.uri, "/info") == 0 ) { server_info(client); } } } return 0; }
static ClientInfo *accept_client( const Socket *listen_socket ){ Socket *new_sock; ClientInfo *res; if( (new_sock = socket_accept( listen_socket )) == NULL ){ camserv_log( MODNAME, "Could not accept new client socket: %s", strerror( errno )); return NULL; } camserv_log( MODNAME, "Accepted new socket: %s", socket_query_remote_name( new_sock )); if( fcntl( socket_query_fd( new_sock ), F_SETFL, O_NONBLOCK ) == -1){ camserv_log( MODNAME, "Unable to set socket to nonblocking mode!"); socket_dest( new_sock ); return NULL; } if( (res = clientinfo_new( new_sock )) == NULL ){ camserv_log( MODNAME, "Error creating clientinfo structure!"); socket_dest( new_sock ); return NULL; } return res; }
static int STDCALL http_server_thread(void* param) { char req[1024] = {0}; bool* running = (bool*)param; socket_t socket = tcpserver_create(NULL, PORT, 32); while(*running) { int r = socket_select_read(socket, 1000); if(1 == r) { struct sockaddr_in in4; socklen_t len = sizeof(in4); socket_t client = socket_accept(socket, (sockaddr*)&in4, &len); if(client != socket_invalid) { r = socket_recv_by_time(client, req, sizeof(req), 0, 5000); r = socket_send_all_by_time(client, s_reply, strlen(s_reply), 0, 5000); r = socket_shutdown(client, SHUT_RDWR); r = socket_close(client); printf("server side close socket\n"); } } } return 0; }
int main(int argc, char *argv[]) { logger = log_create("Log.txt", "NODO", false, LOG_LEVEL_DEBUG); fd = socket_listen(30123); sock_job = socket_accept(fd); log_info(logger,"fd : %d", fd); log_info(logger,"conexion job: %d", sock_job); int hand = socket_handshake_to_client(sock_job, HANDSHAKE_NODO, HANDSHAKE_JOB); if (!hand) { printf("Error al conectar con Job \n"); return EXIT_FAILURE; } void *buffer; size_t sbuffer = 0; int recibi; recibi = socket_recv_packet(sock_job, &buffer, &sbuffer); log_info(logger,"Recibi todo ok : %d\n",recibi); desserializeMap(buffer); /* recvOrder(fd); serializeMapResult(fd, true, 1); recvOrder(fd); char failedTemp[60]; memset(failedTemp, '\0', sizeof(char) * 60); strcpy(failedTemp, "TemporalFallido"); serializeReduceResult(fd, false, 0, failedTemp); recvOrder(fd); */ log_destroy(logger); return EXIT_SUCCESS; }
THREAD_PROC ThreadedSocketAcceptor::socketAcceptorThread( void* p ) { AcceptorThreadInfo * info = reinterpret_cast < AcceptorThreadInfo* > ( p ); ThreadedSocketAcceptor* pAcceptor = info->m_pAcceptor; int s = info->m_socket; int port = info->m_port; delete info; int noDelay = 0; int sendBufSize = 0; int rcvBufSize = 0; socket_getsockopt( s, TCP_NODELAY, noDelay ); socket_getsockopt( s, SO_SNDBUF, sendBufSize ); socket_getsockopt( s, SO_RCVBUF, rcvBufSize ); int socket = 0; while ( ( !pAcceptor->isStopped() && ( socket = socket_accept( s ) ) >= 0 ) ) { if( noDelay ) socket_setsockopt( socket, TCP_NODELAY ); if( sendBufSize ) socket_setsockopt( socket, SO_SNDBUF, sendBufSize ); if( rcvBufSize ) socket_setsockopt( socket, SO_RCVBUF, rcvBufSize ); Sessions sessions = pAcceptor->m_portToSessions[port]; ThreadedSocketConnection * pConnection = new ThreadedSocketConnection ( socket, sessions, pAcceptor->getLog() ); ConnectionThreadInfo* info = new ConnectionThreadInfo( pAcceptor, pConnection ); { Locker l( pAcceptor->m_mutex ); std::stringstream stream; stream << "Accepted connection from " << socket_peername( socket ) << " on port " << port; if( pAcceptor->getLog() ) pAcceptor->getLog()->onEvent( stream.str() ); thread_id thread; if ( !thread_spawn( &socketConnectionThread, info, thread ) ) { delete info; delete pConnection; } else pAcceptor->addThread( socket, thread ); } } if( !pAcceptor->isStopped() ) pAcceptor->removeThread( s ); return 0; }
int nettest6(void) { int err; sockaddr addr; int new_fd; fd = socket_create(SOCK_PROTO_TCP, 0); printf("created socket, fd %d\n", fd); if(fd < 0) return 0; memset(&addr, 0, sizeof(addr)); addr.addr.len = 4; addr.addr.type = ADDR_TYPE_IP; addr.port = 1900; NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(0,0,0,0); err = socket_bind(fd, &addr); printf("socket_bind returns %d\n", err); if(err < 0) return 0; err = socket_listen(fd); printf("socket_listen returns %d\n", err); if(err < 0) return 0; for(;;) { int saved_stdin, saved_stdout, saved_stderr; char *argv; new_fd = socket_accept(fd, &addr); printf("socket_accept returns %d\n", new_fd); if(new_fd < 0) continue; saved_stdin = dup(0); saved_stdout = dup(1); saved_stderr = dup(2); dup2(new_fd, 0); dup2(new_fd, 1); dup2(new_fd, 2); close(new_fd); // XXX launch argv = "/boot/bin/shell"; err = _kern_proc_create_proc("/boot/bin/shell", "shell", &argv, 1, 5, 0); dup2(saved_stdin, 0); dup2(saved_stdout, 1); dup2(saved_stderr, 2); close(saved_stdin); close(saved_stdout); close(saved_stderr); printf("_kern_proc_create_proc returns %d\n", err); } }
int main(void) { // initializing first three investors for program to start with // initializing_END int PORT = 5000; lib_init(); winSock = socket_new(); db_t * db = db_new("teacher.db"); // Checking if socket is not busy, closing app if it is if (socket_bind(winSock, PORT) == SOCKET_ERROR) { printf("Cannot bind %i port\n", PORT); socket_close(winSock); socket_free(winSock); return 0; } socket_listen(winSock); char buf[10000]; socket_t * client = NULL; // main cycle of the program while (1) { printf("Awaiting for connections...\n"); client = socket_accept(winSock); // Checking if client is not null, closing app if he is if (client == NULL) { printf("NULL client, closing app...\n"); break; } int readStatus = socket_read(client, buf, sizeof(buf)); // Skipping empty request (may appear from time to time) if (readStatus <= 0) { printf("Empty request, skipping...\n"); socket_close(client); socket_free(client); continue; } // Printing info about the received request to console printf(">> Got request (readStatus: %i):\n'%s'\n", readStatus, buf); http_request_t request = http_request_parse(buf); // check the type/path of request (API/HTML) & analyze the method (GET/POST/DELETE) // and provide the client with proper answer server_analyzeRequest(&request, client, db); socket_free(client); } // end of program socket_close(winSock); socket_free(winSock); db_free(db); lib_free(); return 0; }
//Accept Function (Accepts a Remote Connection to a Local Socket) msl::socket msl::socket::accept() { msl::socket ret; if(available()>0) ret._socket=socket_accept(_socket,ret._address); return ret; }
tw_net_node * tw_socket_create_onport(tw_node src, tw_node dst, tw_port port, int blocking) { tw_net_node *master = g_tw_net_node[0]; tw_net_node *node; unsigned int i; node = (tw_net_node *) tw_calloc(TW_LOC, "socket-tcp", sizeof(tw_net_node), 1); if (NULL == node) tw_error(TW_LOC, "Could not allocate mem for node."); node->clients = tw_calloc(TW_LOC, "socket-tcp", sizeof(int) * (nnodes - 1), 1); node->socket_sz = sizeof(node->socket); node->socket_fd = -1; /* * If mynode == dest, then create server socket, other create client */ if (dst == g_tw_mynode) { //node->socket_fd = tw_server_socket_create(node->socket, port); socket_accept(node, (nnodes - 1)); if (!blocking) { for (i = 0; i < (nnodes - 1); i++) { fcntl(node->clients[i], F_SETFL, O_NONBLOCK); } } #if VERIFY_SOCKET_TCP printf("Node %d (master) recv's events on port %d \n", src, port); #endif } else { node->socket_fd = tw_client_socket_create(master->hostname, &node->socket, port); printf("%d: client socket fd created %d \n", g_tw_mynode, node->socket_fd); socket_connect(node, node->socket_fd); if (!blocking) { fcntl(node->socket_fd, F_SETFL, O_NONBLOCK); } #if VERIFY_SOCKET_TCP printf("Node %d (remote node) sends events on port %d \n", src, port); #endif } return node; }
static void listen_callback(int fd){ int sockstat = socket_accept(fd,"read_callback","write_callback"); if(sockstat < 0){ debug("Couldn't accept on socket. errorcode: "+sockstat); return; } debug("echo server: listening."); }
/** * The listener thread main function. The listener listens for * connections from clients. */ static void *listener_main(void *arg_p) { struct http_server_t *self_p = arg_p; struct http_server_listener_t *listener_p; struct http_server_connection_t *connection_p; struct inet_addr_t addr; thrd_set_name(self_p->listener_p->thrd.name_p); listener_p = self_p->listener_p; if (socket_open_tcp(&listener_p->socket) != 0) { log_object_print(NULL, LOG_ERROR, FSTR("Failed to open socket.")); return (NULL); } if (inet_aton(listener_p->address_p, &addr.ip) != 0) { return (NULL); } addr.port = listener_p->port; if (socket_bind(&listener_p->socket, &addr) != 0) { log_object_print(NULL, LOG_ERROR, FSTR("Failed to bind socket.")); return (NULL); } if (socket_listen(&listener_p->socket, 3) != 0) { log_object_print(NULL, LOG_ERROR, FSTR("Failed to listen on socket.")); return (NULL); } /* Wait for clients to connect. */ while (1) { /* Allocate a connection. */ connection_p = allocate_connection(self_p); /* Wait for a client to connect. */ socket_accept(&listener_p->socket, &connection_p->socket, &addr); handle_accept(self_p, connection_p); } return (NULL); }
int client_init(int s) { sockinfo *i; struct client *c; int newfd; i = socket_accept(s); if(!i) return 0; /* We have the connection details, but not the actual * file decriptor itself, use socket.c to extract it * for us. */ newfd = socket_get(i); /* First new client - list needs creating */ if(!clients) { clients = calloc(newfd, sizeof(struct client *)); maxfd = newfd; } /* This fd is the largest fd we've ever seen * so the client array won't be big enough for it. * Reallocate it big enough for the new fd * and zero all of the memory between the * previous biggest and the new biggest. */ if(newfd > maxfd) { clients = realloc(clients, sizeof(struct client *) * (newfd + 1)); memset(&clients[maxfd + 1], 0, (newfd - maxfd) * sizeof(struct client *)); maxfd = newfd; } c = malloc(sizeof(struct client)); c->si = i; c->buffer = buffer_init(); c->ch = character_init(c); c->state = CONNECTING; clients[newfd] = c; parse(c); /* The server wants this fd so it can update the * file descriptor read set. */ return newfd; }
int simple_accept(int fd){ int ret; for(;;){ if( (ret = socket_accept(fd, NULL, NULL)) <= 0 && IS_INTERRUPTED){ continue; } else{ break; } } return ret; }
/*-------------------------------------------------------------------------*\ * Tries to accept a socket \*-------------------------------------------------------------------------*/ const char *inet_tryaccept(p_socket server, int family, p_socket client, p_timeout tm) { socklen_t len; t_sockaddr_storage addr; if (family == PF_INET6) { len = sizeof(struct sockaddr_in6); } else { len = sizeof(struct sockaddr_in); } return socket_strerror(socket_accept(server, client, (SA *) &addr, &len, tm)); }