//接收连接回调
int32_t CInsideSocket::OnAccept(SocketFD nAcceptFD, struct sockaddr_in stPeerAddress,
		socklen_t nPeerAddressLen)
{
	CSocket *pSocket = g_FrameSocketMgt.CreateSocket(m_nListenPort);//g_FrameSocketMgt.CreateInsideSocket();
	if(pSocket == NULL)
	{
		g_FrameLogEngine.WriteNetioLog(enmLogLevel_Error, "[%s:%d]create socket object error!\n", 
			__FILE__, __LINE__);
		return -1;
	}

	if(m_pEpoll == NULL)
	{
		g_FrameLogEngine.WriteNetioLog(enmLogLevel_Error, "m_pEpoll is null!\n");
		return -1;
	}

	pSocket->Clear();
	pSocket->SetSocketFD(nAcceptFD);
	pSocket->SetSocketStatus(enmSocketStatus_Connected);
	pSocket->SetPeerAddress((uint32_t)stPeerAddress.sin_addr.s_addr);
	pSocket->SetPeerPort(stPeerAddress.sin_port);
	pSocket->SetCreateTime(time(NULL));
	pSocket->SetEpollObj(m_pEpoll);

	m_pEpoll->RegistEvent(pSocket, EPOLLIN | EPOLLOUT);

	set_non_block(nAcceptFD);

	return S_OK;
}
/*
 * select reckons that we have someone wanting to connect to us
 * - let them.
 */
static void add_client(int server)
{
    int saclientlen, client;
    struct sockaddr_in saclient;
    command* cmd;

    saclientlen = sizeof (saclient);
    client = accept (server, (struct sockaddr *) &saclient, &saclientlen);

    /* The accept failed, either an error, or there is no one there */
    if (client == -1)
    {
	if(errno != EWOULDBLOCK)
	{
	    perror (progname);
	    exit (EXIT_FAILURE);
	}

	return;
    }

    if((print_output & 2) != 0)
	printf ("Accepted\n");

    set_non_block(client);

    write (client, "hello\r\n", 7);

    cmd = malloc(sizeof(command));
    cmd->ptr = 0;
    cmd->handle = client;
    cmd->next = cmd_head;
    cmd_head = cmd;
}
void accept_new_session( int32_t fd, int16_t ev, void * arg )
{
    evsets_t coreset = ( evsets_t )arg;

    if ( ev & EV_READ )
    {
        char dsthost[20];
        uint16_t dstport = 0;

        int32_t newfd = tcp_accept( fd, dsthost, &dstport );
        if ( newfd > 0 )
        {
            set_non_block( newfd );

            event_t event = event_create();
            if ( event == NULL )
            {
                printf( "accept new fd failed .\n" );
                return;
            }

            event_set( event, newfd, EV_READ|EV_PERSIST );
            event_set_callback( event, process_message, event );
            evsets_add( coreset, event, 0 );
        }
    }
}
Exemple #4
0
void iolayer_server_option( int32_t fd )
{
    int32_t flag = 0;
    struct linger ling;

    // Socket非阻塞
    set_non_block( fd );

    flag = 1;
    setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag) );

    flag = 1;
    setsockopt( fd, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(flag) );

#if SAFE_SHUTDOWN
    ling.l_onoff = 1;
    ling.l_linger = MAX_SECONDS_WAIT_FOR_SHUTDOWN;
#else
    ling.l_onoff = 1;
    ling.l_linger = 0;
#endif
    setsockopt( fd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling) );

    // 发送接收缓冲区
#if SEND_BUFFER_SIZE > 0
    //    int32_t sendbuf_size = SEND_BUFFER_SIZE;
    //    setsockopt( fd, SOL_SOCKET, SO_SNDBUF, (void *)&sendbuf_size, sizeof(sendbuf_size) );
#endif
#if RECV_BUFFER_SIZE > 0
    //    int32_t recvbuf_size = RECV_BUFFER_SIZE;
    //    setsockopt( fd, SOL_SOCKET, SO_RCVBUF, (void *)&recvbuf_size, sizeof(recvbuf_size) );
#endif
}
Exemple #5
0
void accept_callback(int fd, short ev, void *arg)
{
	int client_fd;
	struct sockaddr_in client_addr;
	socklen_t client_len = sizeof(client_addr);
	struct client *client;

	printf("call accept_callback\n");

	client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
	if (client_fd < 0) {
		printf("warn: client: accept() failed\n");
		return;
	}

	set_non_block(client_fd);

	client = (struct client*)calloc(1, sizeof(*client));
	if (client == NULL) {
		printf("error: malloc failed\n");
	}
	client->fd = client_fd;
	client->buf_ev = bufferevent_new(client_fd,
			buf_read_callback,
			buf_write_callback,
			buf_error_callback,
			client);

	// Enable a bufferevent.
	// @param event any combination of EV_READ | EV_WRITE.
	bufferevent_enable(client->buf_ev, EV_READ);
}
Exemple #6
0
int grpc_tcp_prepare_socket(SOCKET sock) {
  if (!set_non_block(sock))
    return 0;
  if (!set_dualstack(sock))
    return 0;
  return 1;
}
Exemple #7
0
int32_t tcp_connect( char * host, uint16_t port, int8_t isasyn )
{
	int32_t fd = -1;
	int32_t rc = -1;

	struct sockaddr_in addr;

	fd = socket( AF_INET, SOCK_STREAM, 0 );
	if ( fd < 0 )
	{
		return -1;
	}

	if ( isasyn != 0 )
	{
		// 指定了异步连接
		set_non_block( fd );
	}

	memset( &addr, 0, sizeof(addr) );
	addr.sin_family = AF_INET;
	addr.sin_port	= htons(port);
	inet_pton(AF_INET, host, (void *)&(addr.sin_addr.s_addr));

	rc = connect( fd, (struct sockaddr *)&addr, sizeof(struct sockaddr) );
	if ( rc == -1 && errno != EINPROGRESS )
	{
		// 连接出错
		close( fd );
		fd = -1;
	}

	return fd;
}
Exemple #8
0
grpc_error *grpc_tcp_prepare_socket(SOCKET sock) {
  grpc_error *err;
  err = set_non_block(sock);
  if (err != GRPC_ERROR_NONE) return err;
  err = set_dualstack(sock);
  if (err != GRPC_ERROR_NONE) return err;
  return GRPC_ERROR_NONE;
}
Exemple #9
0
int
after_pass_data(int ret, struct author *author, mbuf_type *mbuf)
{
    struct epoll_event ev = {0};
    int fd;
    if (ret == 0)
        return 0;
    if (mbuf == NULL)
        return -1;
    if (ret < 0)                //tcp needed.
    {
        //printf("tcp needed\n");
        ret = ret + 1;
        ret = -ret;
        
        if ((mbuf->tcpfd > 0) && ((mbuf->qtimes % (MAX_TRY_TIMES / 3)) == 0))       //retry tcp
        {
            ev.data.fd = mbuf->tcpfd;
            mbuf->tcpfd = 0;
            author->tcpinuse--;
            epoll_ctl(author->bdepfd, EPOLL_CTL_DEL, ev.data.fd, &ev);
            close(ev.data.fd);
        }
        if (mbuf->tcpfd > 0)      //processing...
            return 0;
        //restart..
        if (author->tcpinuse > (LIST_SPACE / 10))
            fd = -1;            //too many tcps
        else {
            mbuf->tcpnums++;
            fd = socket(AF_INET, SOCK_STREAM, 0);
        }
        if (fd > 0) {
            author->tcpinuse++;
            mbuf->tcpfd = fd;
            mbuf->socktype = TCP;
            ev.data.fd = fd;
            ev.events = EPOLLOUT;       //wait for ready to write
            author->eptcpfds[fd].ret = ret;
            memcpy(author->eptcpfds[fd].domain, mbuf->td, mbuf->dlen);
            set_non_block(fd);
            set_recv_timeout(fd, 0, 500);       //half second
            epoll_ctl(author->bdepfd, EPOLL_CTL_ADD, fd, &ev);
            query_from_auth_tcp(author, mbuf);
            return 0;
        } else
            ret++;              //fix ret value, for deleting afterword
    }

    if (ret > 0)                //delete qoutinfo
    {
        ret = ret - 1;          //minus the 1 p_a_d added
        release_qoutinfo(author, mbuf, ret);
    }
    return 0;
}
Exemple #10
0
static int
create_listen_ports(int port, int proto, uchar * addr)
{
    int fd = -1;
    fd = create_socket(port, proto, addr);
    if (fd < 0 || set_non_block(fd) < 0) {
        printf("port:%d,proto:%d\n", port, proto);
        dns_error(0, "fd < 0");
    }
    return fd;
}
Exemple #11
0
int main(int argc,char **argv)
{
    if(argc<3)
        {
            printf("usage:server [SERVER_IP] [SERVER_PORT]\n");
            exit(0);
        }
    int port=atoi(argv[2]);
    char *ip=argv[1];
    struct sockaddr_in ser;
    ser.sin_addr.s_addr=inet_addr(ip);
    ser.sin_family=AF_INET;
    ser.sin_port=htons(port);
    int sockfd;
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    int i=bind(sockfd,(struct sockaddr*)&ser,sizeof(ser));
    if(i!=0)
        {
            printf("#BIND PORT ERROR#\n");
            exit(0);
        }
    signal_add(SIGCHLD);
    set_non_block(sockfd);
    server_static_init(sockfd);
    listen(sockfd,5);
    int t;
    for(i=0;i<PROCESS_NUM;i++)
        {
            t=fork();
            if(t==0)
                {
                    process();
                    exit(0);
                }
            else if(t<0)
                {
                    printf("#fork error#");
                    exit(0);
                }
            else
                {
                    fork_mark[fork_id]=t;
                    fork_id++;
                }
        }
    while(1)
        {
            server_running_update();
        }
}
Exemple #12
0
        MmspSession::MmspSession(
            MmspdModule & mgr)
            : util::protocol::MmspServer(mgr.io_svc())
            , mgr_(mgr)
            , session_id_(0)
            , dispatcher_(NULL)
            , file_id_(0)
            , play_count_(0)
            , play_incarnation_(0)
        {
            static boost::uint32_t g_id = 0;
            session_id_ = ++g_id;

            boost::system::error_code ec;
            set_non_block(true, ec);
        }
Exemple #13
0
void
server_test(as_lua_pconf_t *cnf) {
  as_cnf_return_t ret = lpconf_get_pconf_value(cnf, 1, "tcp_port");
  int sock;
  sock = make_server_socket(ret.val.i);
  if (sock < 0) {
    exit(EXIT_FAILURE);
  }
  set_non_block(sock);
  if (listen(sock, 500) < 0) {
    perror("listen");
    exit(EXIT_FAILURE);
  }
  // select_server(sock);
  // epoll_server(sock);
  test_worker_process(sock, cnf);
  close(sock);
}
Exemple #14
0
int main(){
	//делаем соект
	static evutil_socket_t master_socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(-1==master_socket)
		std::cout << "socket():\n"<<errno<<std::endl;
	else{
		//делаем структуру
		struct sockaddr_in sa;
		sa.sin_family=AF_INET;
		sa.sin_port=htons(12345);
		sa.sin_addr.s_addr=htonl(INADDR_ANY);
		//биндим
		if(bind(master_socket,(sockaddr*)&sa,sizeof(sa))==-1)
			std::cout << "bind:\n"<<errno<<std::endl;
		else if(listen(master_socket,SOMAXCONN)==-1)
			std::cout << "listen:\n"<<errno<<std::endl;
		else{
			//повторное использование мастер сокета
			int optval = 1;
			setsockopt(master_socket,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(optval));
			//не  блокирующий
			set_non_block(master_socket);
			                                                               
			//делаем ядро
			struct event_base * base=event_base_new();
	
			//регистрируем события
			struct event * evn=event_new(base,master_socket,EV_READ|EV_PERSIST,cb_master,event_self_cbarg());
			event_add(evn,NULL);

			//запускаем цикл
			event_base_dispatch(base);
			
			//очищаем
			event_base_free(base);
			event_free(evn);
			//закрываем
			shutdown(master_socket,SHUT_RDWR);
			close(master_socket);
	
		}
	}
	return 0;
}
Exemple #15
0
void iolayer_client_option( int32_t fd )
{
    int32_t flag = 0;

    // Socket非阻塞
    set_non_block( fd );

    flag = 1;
    setsockopt( fd, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(flag) );

    // 发送接收缓冲区
#if SEND_BUFFER_SIZE > 0
    //    int32_t sendbuf_size = SEND_BUFFER_SIZE;
    //    setsockopt( fd, SOL_SOCKET, SO_SNDBUF, (void *)&sendbuf_size, sizeof(sendbuf_size) );
#endif
#if RECV_BUFFER_SIZE > 0
    //    int32_t recvbuf_size = RECV_BUFFER_SIZE;
    //    setsockopt( fd, SOL_SOCKET, SO_RCVBUF, (void *)&recvbuf_size, sizeof(recvbuf_size) );
#endif
}
Exemple #16
0
// [-2, +1, e]
static int
lcf_socket_new(lua_State *L) {
  const char *host = luaL_checkstring(L, 1);
  int port = luaL_checkinteger(L, 2);

  lbind_checkregvalue(L, LRK_WORKER_CTX, LUA_TLIGHTUSERDATA,
                      "no worker ctx");
  as_mw_worker_ctx_t *ctx = (as_mw_worker_ctx_t *)lua_touserdata(L, -1);

  lbind_get_thread_local_vars(L, 1, LLK_THREAD);
  as_thread_t *th = (as_thread_t *)lua_touserdata(L, -1);

  as_lm_socket_t *sock = (as_lm_socket_t *)lua_newuserdata(
      L, sizeof(as_lm_socket_t));
  sock->res = NULL;
  sock->type = LM_SOCK_TYPE_CUSTOM;

  luaL_getmetatable(L, LM_SOCKET);
  lua_setmetatable(L, -2);

  sock->res = (as_thread_res_t *)memp_alloc(
      ctx->mem_pool, sizeof_thread_res(int));
  if (sock->res == NULL) {
    lua_pushstring(L, "alloc error");
    lua_error(L);
  }

  int fd = make_client_socket(host, port);
  if (fd < 0) {
    memp_recycle(sock->res);
    lua_pushstring(L, "connect error");
    lua_error(L);
  }
  set_non_block(fd);
  *((int *)sock->res->d) = fd;
  asthread_res_init(sock->res, res_free_f, res_fd_f);
  asthread_res_add_to_th(sock->res, th);
  asthread_res_ev_init(sock->res, ctx->epfd);

  return 1;
}
void listenfd_options( int32_t fd )
{
    int32_t flags = 0;
    struct linger ling;

    /* TCP Socket Option Settings */
    flags = 1;
    setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags) );

    flags = 1;
    setsockopt( fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags) );

    flags = 1;
    setsockopt( fd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags) );
    setsockopt( fd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling) );

#if defined (__linux__)
	flags = 1;
	setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags) );
#endif

    set_non_block( fd );
}
Exemple #18
0
static
struct conn_t *conn_new(struct sockaddr_in *raddr, struct sockaddr_in *laddr) {
    struct conn_t *c;
    int lsize, errnosave;
    struct sockaddr_in tmp;

    c = smalloc(sizeof(*c));
    memset(c, 0, sizeof(*c));
    c->state = CONN_NEW;
    INIT_LIST_HEAD(&c->reqs);

    if ((c->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
	errnosave = errno;
	syslog(LOG_ERR, "socket: %s", strerror(errno));
	free(c);
	errno = errnosave;
	return 0;
    }

    /* If this is not the first connection, do a non-blocking connect */
    if (!list_empty(&clist))
	set_non_block(c->fd);

    tmp = *laddr;		/* use a temp here because
				 * bindresvport writes it. */
    if (laddr->sin_port ||
	bindresvport(c->fd, &tmp) == -1) {
	    syslog(LOG_ERR, "bindresvport: %s (ignoring)", strerror(errno));
	    /* If we specified a port or failed to bind to a reserved
	     * port for some reason, try a normal bind. */
	    if (bind(c->fd, (struct sockaddr *) laddr, sizeof(*laddr)) == -1) {
		errnosave = errno;
		syslog(LOG_ERR, "bind(%s:%d): %s (ignoring)",
		       inet_ntoa(laddr->sin_addr), ntohs(laddr->sin_port),
		       strerror(errno));
		close(c->fd);
		free(c);
		errno = errnosave;
		return 0;
	    }
    }

    if (verbose)
	syslog(LOG_INFO, "Connecting to %s:%d...",
	       inet_ntoa(raddr->sin_addr), ntohs(raddr->sin_port));

    if (connect(c->fd, (struct sockaddr *) raddr, sizeof(*raddr)) == -1) {
	if (errno != EINPROGRESS) {
	    errnosave = errno;
	    syslog(LOG_ERR, "connect(%s:%d): %s",
		   inet_ntoa(raddr->sin_addr), ntohs(raddr->sin_port),
		   strerror(errno));
	    close(c->fd);
	    free(c);
	    errno = errnosave;
	    return 0;
	}
    }

    /* Make note of our local address */
    lsize = sizeof(c->laddr);
    getsockname(c->fd, (struct sockaddr *)&c->laddr, &lsize);
    c->raddr = *raddr;

    /* Prime output buffer with version information and cookie */
    conn_send_version(c);

    set_keep_alive(c->fd);
    set_no_delay(c->fd);
    set_non_block(c->fd);

    /* Append to list of connections */
    list_add_tail(&c->list, &clist);
    return c;
}
Exemple #19
0
int handle_commands_from_main(struct worker_st *ws)
{
	uint8_t cmd;
	size_t length;
	uint8_t cmd_data[1536];
	UdpFdMsg *tmsg = NULL;
	int ret;
	int fd = -1;
	/*int cmd_data_len;*/

	memset(&cmd_data, 0, sizeof(cmd_data));

	ret = recv_msg_data(ws->cmd_fd, &cmd, cmd_data, sizeof(cmd_data), &fd);
	if (ret < 0) {
		oclog(ws, LOG_DEBUG, "cannot obtain data from command socket");
		exit_worker_reason(ws, REASON_SERVER_DISCONNECT);
	}

	if (ret == 0) {
		oclog(ws, LOG_ERR, "parent terminated");
		return ERR_NO_CMD_FD;
	}

	length = ret;

	oclog(ws, LOG_DEBUG, "worker received message %s of %u bytes\n", cmd_request_to_str(cmd), (unsigned)length);

	/*cmd_data_len = ret - 1;*/

	switch(cmd) {
		case CMD_TERMINATE:
			exit_worker_reason(ws, REASON_SERVER_DISCONNECT);
		case CMD_UDP_FD: {
			unsigned has_hello = 1;

			if (ws->udp_state != UP_WAIT_FD) {
				oclog(ws, LOG_DEBUG, "received another a UDP fd!");
			}

			tmsg = udp_fd_msg__unpack(NULL, length, cmd_data);
			if (tmsg) {
				has_hello = tmsg->hello;
			}

			if (fd == -1) {
				oclog(ws, LOG_ERR, "received UDP fd message of wrong type");
				goto udp_fd_fail;
			}

			set_non_block(fd);

			if (has_hello == 0) {
				/* check if the first packet received is a valid one -
				 * if not discard the new fd */
				if (!recv_from_new_fd(ws, fd, tmsg)) {
					oclog(ws, LOG_INFO, "received UDP fd message but its session has invalid data!");
					if (tmsg)
						udp_fd_msg__free_unpacked(tmsg, NULL);
					close(fd);
					return 0;
				}
				RESET_DTLS_MTU(ws);
			} else { /* received client hello */
				ws->udp_state = UP_SETUP;
			}

			if (ws->dtls_tptr.fd != -1)
				close(ws->dtls_tptr.fd);
			if (ws->dtls_tptr.msg != NULL)
				udp_fd_msg__free_unpacked(ws->dtls_tptr.msg, NULL);

			ws->dtls_tptr.msg = tmsg;
			ws->dtls_tptr.fd = fd;

			oclog(ws, LOG_DEBUG, "received new UDP fd and connected to peer");
			return 0;

			}
			break;
		default:
			oclog(ws, LOG_ERR, "unknown CMD 0x%x", (unsigned)cmd);
			exit_worker_reason(ws, REASON_ERROR);
	}

	return 0;

udp_fd_fail:
	if (tmsg)
		udp_fd_msg__free_unpacked(tmsg, NULL);
	if (ws->dtls_tptr.fd == -1)
		ws->udp_state = UP_DISABLED;

	return -1;
}
Exemple #20
0
int main(int argc, char* argv[]) {
  int listen_fd, ret;
  int epoll_fd;
  struct epoll_event event;
  struct epoll_event *events;

  listen_fd = create_and_bind(PORT);
  if (listen_fd == -1) {
    return -1;
  }

  ret = set_non_block(listen_fd);
  if (ret == -1) {
    return -1;
  }

  ret = listen(listen_fd, SOMAXCONN);
  if (ret == -1) {
    perror("listen");
    return -1;
  }

  epoll_fd = epoll_create1(0);
  if (epoll_fd == -1) {
    perror("epoll_create");
    return -1;
  }

  event.data.fd = listen_fd;
  event.events = EPOLLIN | EPOLLET;
  ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &event);
  if (ret == -1) {
    perror("epoll_ctl");
    return -1;
  }

  events = calloc(MAX_EVENTS, sizeof event);

  for (;;) {
    int n, i;

    n = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
    for (i = 0; i < n; i++) {
      if (events[i].events & EPOLLERR || events[i].events & EPOLLHUP || !events[i].events & EPOLLIN) {
        fprintf(stderr, "epoll error\n");
        close(events[i].data.fd);
        continue;
      } else if (listen_fd == events[i].data.fd) {
        for (;;) {
          struct sockaddr in_addr;
          socklen_t in_len;
          int in_fd;
          char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

          in_len = sizeof in_addr;
          in_fd = accept(listen_fd, &in_addr, &in_len);
          if (in_fd == -1) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
              break;
            } else {
              perror("accpet");
              break;
            }
          }

          ret = getnameinfo(&in_addr, in_len, hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV);
          if (ret == 0) {
            printf("accept connection on fd %d, [%s:%s]\n",  in_fd, hbuf, sbuf);
          }

          ret = set_non_block(in_fd);
          if (ret == -1) {
            return -1;
          }

          event.data.fd = in_fd;
          event.events = EPOLLIN | EPOLLET;
          ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, in_fd, &event);
          if (ret == -1) {
            perror("epoll_ctl");
            return -1;
          }
        }
        continue;
      } else if (events[i].events & EPOLLIN) {
        // get request
        int done = 0;

        for (;;) {
          ssize_t count;
          char buf[512];

          count = read(events[i].data.fd, buf, sizeof buf);
          if (count == -1) {
            if (errno != EAGAIN) {
              perror("read");
              done = 1;
              break;
            }

            event.events = EPOLLOUT | EPOLLET;
            event.data.fd = events[i].data.fd;
            ret = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, events[i].data.fd, &event);
            if (ret == -1) {
              perror("epoll_ctl:mod");
              done = 1;
            }

            break;
          } else if (count == 0) {
            done = 1;
            break;
          }

          // 写入标准输出
          ret = write(1, buf, count);
          if (ret == -1) {
            perror("write");
            done = 1;
            break;
          }
        }

        if (done == 1) {
          close(events[i].data.fd);
        }
      } else if (events[i].events & EPOLLOUT) {
        // response
        int fd;
        int done = 0;
        size_t size = 512;
        ssize_t count;

        fd = open("./epoll-server.c", O_RDONLY | O_NONBLOCK);
        if (fd == -1) {
          perror("open");
          close(events[i].data.fd);
          return -1;
        }

        char *head = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
        count = write(events[i].data.fd, head, sizeof head);
        if (count == -1 && errno != EAGAIN) {
          perror("write");
          close(events[i].data.fd);
          return -1;
        }

        for (;;) {
          count = sendfile(events[i].data.fd, fd, 0, size);
          if (count == -1) {
            if (errno != EAGAIN) {
              perror("sendfile");
              done = 1;
            }
            break;
          } else if (count == 0) {
            done = 1;
            break;
          }
        }

        if (done == 1) {
          close(events[i].data.fd);
        }

      }
    }
  }

  free(events);
  return 0;
}
int main( int argc, char ** argv )
{
    if ( argc != 2 )
    {
        printf("echoserver [port] .\n");
        return 0;
    }

    evsets_t coreset = evsets_create();
    if ( coreset == NULL )
    {
        printf( "create core event sets failed .\n" );
        goto FINAL;
    }

    signal( SIGPIPE, SIG_IGN );
    signal( SIGINT, echoserver_signal_handler );
    signal( SIGTERM, echoserver_signal_handler );

    // listen port
    uint16_t port = (uint16_t)atoi( argv[1] );
    int32_t fd = tcp_listen( "127.0.0.1", port, listenfd_options );
    if ( fd < 0 )
    {
        printf( "listen failed %d .\n", port );
        goto FINAL;
    }
    set_non_block( fd );
    event_t evaccept = event_create();
    if ( evaccept == NULL )
    {
        printf( "create accept event failed .\n" );
        goto FINAL;
    }
    event_set( evaccept, fd, EV_READ|EV_PERSIST );
    event_set_callback( evaccept, accept_new_session, coreset );
    evsets_add( coreset, evaccept, 0 );

    // running ...
    isrunning = 1;
    while ( isrunning == 1 )
    {
        evsets_dispatch( coreset );
    }

FINAL :
    if ( evaccept != NULL )
    {
        event_destroy( evaccept );
    }

    if ( fd > 0 )
    {
        close( fd );
    }

    if ( coreset != NULL )
    {
        evsets_destroy( coreset );
    }

    return 0;
}
//打开服务器套接字
int32_t CTCPSocket::OpenAsServer(uint16_t nPort, const char* szLocalIP/* = NULL*/, bool nNonBlock/*= true*/)
{
	//若socket连接已存在则先关闭套接字
	if (enmInvalidSocketFD != m_socketFD)
	{
		CloseSocket();
	}

#ifdef WIN32
	//创建socket
	m_socketFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (enmInvalidSocketFD == m_socketFD)
	{
		return E_SOCKETCREATE;
	}

	//设置套接字属性
	int32_t op = 1;
	int32_t ret = setsockopt(m_socketFD, SOL_SOCKET, SO_REUSEADDR, (const char*)&op, sizeof(op));
	if (0 != ret)
	{
		CloseSocket();
		return E_SOCKETOPTION;
	}
#else
	//打开套接字
	m_socketFD = socket(AF_INET, SOCK_STREAM, 0);
	if (enmInvalidSocketFD == m_socketFD)
	{
		return E_SOCKETCREATE;
	}

	//设置套接字属性
	int32_t op = 1;
	int32_t ret = setsockopt(m_socketFD, SOL_SOCKET, SO_REUSEADDR, &op, sizeof(op));
	if (0 != ret)
	{
		CloseSocket();
		return E_SOCKETOPTION;
	}
#endif

	//填充服务器地址&端口信息
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = ((NULL != szLocalIP) ? inet_addr(szLocalIP) : htonl(INADDR_ANY));
	addr.sin_port = htons(nPort);

	ret = bind(m_socketFD, (struct sockaddr *)&addr, sizeof(addr));
	if (0 != ret)
	{
		CloseSocket();
		return E_SOCKETBIND;
	}

	//开始监听
	ret = listen(m_socketFD, SOMAXCONN);
	if (0 != ret)
	{
		CloseSocket();
		return E_SOCKETLISTEN;
	}

#ifndef WIN32
	//设置为非阻塞
	if(nNonBlock)
	{
		set_non_block(m_socketFD);
	}

#endif


	//更新套接字类型和状态
	m_socketType = enmSocketType_Listen;
	m_socketStatus = enmSocketStatus_Opened;

	return S_OK;

}
//与服务端建立连接
int32_t CTCPSocket::Connect(uint32_t nRemoteIP, uint16_t nPort, bool bNonBlock/* = true*/, int32_t nTimeout/* = 0*/)
{
	//判断套接字类型
	if (enmSocketType_Communicate != m_socketType)
	{
		return E_SOCKETTYPE;
	}

	//套接字是否打开
	if ((enmInvalidSocketFD == m_socketFD) || (enmSocketStatus_Opened != m_socketStatus))
	{
		return E_SOCKETNOTCREATED;
	}

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = nRemoteIP;
	addr.sin_port = htons(nPort);

	if (bNonBlock)
	{
#ifndef WIN32
		set_non_block(m_socketFD);
#else
		unsigned long ul = 1;
		int32_t ret = ioctlsocket(m_socketFD, FIONBIO, (unsigned long*)&ul);
		if (ret == SOCKET_ERROR)
		{
			return E_SOCKETCONTROL;
		}
#endif
	}

	//与服务器端建立连接
	int32_t ret = connect(m_socketFD, (const struct sockaddr*)&addr, sizeof(addr));
	if (0 != ret)
	{
		CloseSocket();
		return E_SOCKETCONNECT;
	}

	//非阻塞并等待超时
	if (bNonBlock && (0 < nTimeout))
	{
		timeval tv;
		tv.tv_sec = nTimeout / MS_PER_SECOND;
		tv.tv_usec = (nTimeout % MS_PER_SECOND) * US_PER_MS;

		fd_set rset;
		fd_set wset;
		FD_ZERO(&rset);
		FD_SET(m_socketFD, &rset);
		wset = rset;

		ret = select((int)m_socketFD + 1, &rset, &wset, NULL, &tv);
		if (0 >= ret)
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#ifndef WIN32
		if ((FD_ISSET(m_socketFD, &rset)) && (FD_ISSET(m_socketFD, &wset)))
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#endif
	}

	//更新套接字状态
	m_socketStatus = enmSocketStatus_Connected;

	return S_OK;
}
//与服务端建立连接
int32_t CTCPSocket::Connect_With_Timeout(const char* szRemoteIP, uint16_t nPort, uint16_t secs, bool bNonBlock/* = true*/)
{
	if (NULL == szRemoteIP)
	{
		return E_REMOTEIP;
	}

	//判断套接字类型
	if (enmSocketType_Communicate != m_socketType)
	{
		return E_SOCKETTYPE;
	}

	//套接字是否打开
	if ((enmInvalidSocketFD == m_socketFD) || (enmSocketStatus_Opened != m_socketStatus))
	{
		return E_SOCKETNOTCREATED;
	}

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(szRemoteIP);
	addr.sin_port = htons(nPort);
	int32_t ret; 
#ifdef WIN32
	if(bNonBlock)
	{
		unsigned long ul = 1;
		ret = ioctlsocket(m_socketFD,FIONBIO,(unsigned long*)&ul);
		if(ret == SOCKET_ERROR)
		{
			return SOCKET_ERROR;
		}
	}
#else
	if (bNonBlock)
	{
		set_non_block(m_socketFD);
	}
#endif

	//与服务器端建立连接
	ret = connect(m_socketFD, (const struct sockaddr*)&addr, sizeof(addr));
	if (0 != ret)
	{
#ifdef WIN32
		if(WSAGetLastError() != WSAEWOULDBLOCK)
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#else
		if(errno != EINPROGRESS)
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#endif

	}
	struct timeval to;
	fd_set rSet,wSet,eSet;
	FD_ZERO(&rSet);
	FD_ZERO(&wSet);
	FD_ZERO(&eSet);
	FD_SET(m_socketFD,&rSet);
	FD_SET(m_socketFD,&wSet);
	FD_SET(m_socketFD,&eSet);
	to.tv_sec = secs;
	to.tv_usec= 0;
#ifdef WIN32
	ret = select(0,&rSet,&wSet,&eSet,&to);
#else
	ret = select(m_socketFD+1,&rSet,&wSet,0,&to);
#endif
	if(ret <= 0)
	{
		//select error or timeout
		CloseSocket();
		return E_SOCKETCONNECT;
	}
#ifdef WIN32
	if (FD_ISSET(m_socketFD,&eSet))
	{
		//error happened
		CloseSocket();
		return E_SOCKETCONNECT;
	}
#else
	if (FD_ISSET(m_socketFD,&rSet) && FD_ISSET(m_socketFD,&wSet))
	{
		//error happened
		CloseSocket();
		return E_SOCKETCONNECT;
	}
#endif

	//更新套接字状态
	m_socketStatus = enmSocketStatus_Connected;

	return S_OK;
}
static void do_server(int port)
{
    fd_set readfds;
    int server;
    struct sockaddr_in saserver;
    command* cp;
    int maxd, n;
    int flg;
    btcli child;
    char buf[2048];

    /* Create a socket, and start listening. */

    server = socket (AF_INET, SOCK_STREAM, 0);
    if (server == -1)
    {
	printf("socket creation failed!\n");
	perror (progname);
	exit (EXIT_FAILURE);
    }

    memset (&saserver, 0, sizeof (saserver));
    saserver.sin_family = AF_INET;
    saserver.sin_addr.s_addr = INADDR_ANY;
    saserver.sin_port = htons (port);

    if (bind (server, (struct sockaddr *) &saserver, sizeof (saserver)))
    {
	printf("socket bind failed!\n");
	perror (progname);
	exit (EXIT_FAILURE);
    }

    if (listen (server, 1))
    {
	printf("listen failed!\n");
	perror (progname);
	exit (EXIT_FAILURE);
    }

    /*
     * This loop below is controlled by ''mode''.  It takes on a
     * number of different values, at different times to mean
     * different things.
     *  RUN	- We might have a BTCLI running, but should
     *            keep pumping data anyway.
     *  DIE	- We should exit as soon as possible.
     *            We should kill btcli, and btclid.
     *            All connected users are dropped
     *  START   - We should start a copy of btcli
     *  STOP    - We should kill the current copy of BTCLI.
     *  RESTART - We should kill btcli, and then start it again
     *  SHELL   - We should stop btcli, run a command and restart btcli
     *  DEVINFO - Output the parameters to btcli
     * 
     */
    mode = MODE_RUN;

    /*
    Change to having one big loop (not two nested)
    Select on the following things:
    ''accept'' on the socket server, so that new people can telnet in.
    ''read'' from each of the sockets for commands.
    ''read'' from stdin, to check that no one is typing on the screen.
    ''read'' from the btcli (if it exists), and buffer the data
    */

    child.pid = 0;
    child.read = child.write = -1;
    start_btcli(&child);

    if((print_output & 2) != 0)
	printf("Starting 'do_server' loop\n");

    set_non_block(server);

    set_non_block(STDIN_FILENO);

    setbuf(stdin, NULL);

    flg = fcntl(STDIN_FILENO, F_GETFL);
/*  if((print_output & 2) != 0)
	printf("STDIN Flags = 0x%x\n", flg);*/

    fcntl(STDIN_FILENO, F_SETFL, flg|O_NDELAY);

    flg = fcntl(STDIN_FILENO, F_GETFL);
/*  if((print_output & 2) != 0)
	printf("STDIN Flags = 0x%x\n", flg);*/

    cmd_stdin.ptr = 0;
    cmd_stdin.handle = STDIN_FILENO;
    cmd_stdin.next = NULL;
    cmd_head = &cmd_stdin;

    do
    {
	FD_ZERO (&readfds);

	FD_SET (server, &readfds);
	maxd = server;

	/* Read from btcli */
	if(child.read != -1)
	{
	    FD_SET (child.read, &readfds);
	    if(child.read > maxd)
		maxd = child.read;
	}

	/* Read from the ''command'' list (stdin and socket connections) */
	for(cp = cmd_head; cp != NULL; cp = cp->next)
	{
	    if (cp->handle >= 0)
	    {
		FD_SET (cp->handle, &readfds);
		if(cp->handle > maxd)
		    maxd = cp->handle;
	    }
	}

	/* Perform the select */
	/* printf ("[%d\n", count_clients()); */
  	n = select (maxd + 1, &readfds, NULL, NULL, NULL);
	/* printf ("]\n"); */

	if (n == -1)
	{
	    printf("select -> got -1\n");
	    perror (progname);
	    continue;
	}

	/* Someone want to connect to the socket */
	if (FD_ISSET (server, &readfds))
	{
	    /* Add to list of clients */
	    add_client(server);
	}

	/* read the output from btcli */
	if (child.read != -1 && FD_ISSET (child.read, &readfds))
	{
	    n = read (child.read, buf, sizeof (buf) - 1);
	    if(n > 0)
	    {
		 /*
		  * (Has anyone noticed this is C, not C++?)
		  * If there isn't a newline at the end, add one.
		  * This is bad if we got a partial line; we
		  * could do tricks with select to help here.
		  */
		 if (n < sizeof(buf) - 1 && buf[n-1] != '\n')
		      buf[n++] = '\n';
		 buf[n] = '\0';

		/* Output the data from btcli to the screen */
		if ((print_output & 1) != 0)
		{
		    printf ("%s\0", buf);
		}

		/* output the data to the sockets */
		write_to_clients(buf, n);
	    }
	    else
	    {
		/* we failed to read anything from btcli (but select said that we could) */
		if (n < 0)
		{
		    printf("read (from child) -> got -1\n");
		    perror (progname);
		}
/*		mode = MODE_RESTART;*/
		/* Wait for explicit instruction to restart */
		mode = MODE_STOP;
	    }
	}

	/* This is where we handle data coming in from the socket
	   connection. */
	for (cp = cmd_head; cp != NULL; cp = cp->next)
	{
	    if (cp->handle >= 0 && FD_ISSET (cp->handle, &readfds))
	    {
#ifdef SIGALRM
		if(cp->handle == STDIN_FILENO)
		    alarm (1);
#endif
		n = read (cp->handle, buf, sizeof (buf) - 1);
#ifdef SIGALRM
		if(cp->handle == STDIN_FILENO)
		    alarm (0);
#endif
		if (n > 0)
		{
		    buf[n] = 0;
		    command_add_frag(cp, child.write, buf, n);
		}
		else
		{
		    if(n < 0)
		    {
			if(errno != EINTR)
			{
			    printf("read (from client) -> got -1\n");
			    perror (progname);
			}
		    }
		    else
		    {
			if((print_output & 2) != 0)
			    printf ("EOF on client\n");
		    }
		    if(cp->handle != STDIN_FILENO)
		    {
			close(cp->handle);	/* Close the socket handle (needed!?) */
			cp->handle = -1;	/* Mark the client for removal */
		    }
		}
	    }
	}
	remove_clients();

	/* Now we do different thing if we have been given a special btclid command */

	switch (mode)
	{
	case MODE_RESTART:

	    if((print_output & 2) != 0)
		printf("ReStarting\n");

	    close_btcli(&child);
	    start_btcli(&child);

	    mode = MODE_RUN;

	    break;

	case MODE_SHELL:

	    close_btcli(&child);

	    if((print_output & 2) != 0)
		printf("Running shell command ''%s''\n", shell);

	    do_system(shell);

	    memset(shell, 0, sizeof(shell));

	    start_btcli(&child);

	    mode = MODE_RUN;

	    break;

	case MODE_DEVINFO:

	    strcpy(buf, "ARGS:");
	    for(n=1; (n<64)&&(args[n]!=NULL); n++)
	    {
		strcat(buf, " ");
		strcat(buf, args[n]);
	    }
	    strcat(buf, "\r\n");

	    write_to_clients(buf, strlen(buf));

	    if((print_output & 1) != 0)
		printf ("%s", buf);

	    mode = MODE_RUN;

	    break;

	case MODE_STOP:

	    if(child.pid != 0)
		close_btcli(&child);

	    mode = MODE_RUN;

	    break;

	case MODE_START:

	    if(child.pid == 0)
		start_btcli(&child);

	    mode = MODE_RUN;

	    break;
	}
    }
    while (mode != MODE_DIE);

    close_btcli(&child);

    close (server);
}
Exemple #26
0
        void HttpProxy::handle_async(
            boost::system::error_code const & ec, 
            Size const & bytes_transferred)
        {
            LOG_SECTION();

            LOG_DEBUG("[handle_async] (id = %u, status = %s, ec = %s, bytes_transferred = %s)" 
                %id_ % state_str[state_] % ec.message() % bytes_transferred.to_string());

            if (watch_state_ == broken) {
                on_finish();
                delete this;
                return;
            }

            if (ec) {
                if (state_ == receiving_request_head) {
                    error_code ec1;
                    response_.clear_data();
                    bool block = !get_non_block(ec1);
                    if (block)
                        set_non_block(true, ec1);
                    boost::asio::read(*this, response_.data(), boost::asio::transfer_at_least(4096), ec1);
                    if (block)
                        set_non_block(false, ec1);
                    LOG_DATA(framework::logger::Debug, ("receiving_request_head", response_.data().data()));
                }
                on_error(ec);
                switch (state_) {
                    case receiving_request_head:
                    case transferring_request_data:
                    case sending_response_head:
                    case transferring_response_data:
                        on_finish();
                        state_ = exiting;
                        if (watch_state_ == watching) {
                            error_code ec1;
                            HttpSocket::cancel(ec1);
                        } else {
                            delete this;
                        }
                        break;
                    case local_processing:
                        if (is_local() && !response_.head().content_length.is_initialized() && bytes_transferred.is_size_t()) {
                            response_.head().content_length.reset(bytes_transferred.get_size_t());
                        }
                    case preparing:
                    case connectting:
                    case sending_request_head:
                    case receiving_response_head:
                        state_ = sending_response_head;
                        response_error(ec, boost::bind(&HttpProxy::handle_async, this, _1, _2));
                        break;
                    default:
                        assert(0);
                        break;
                }
                return;
            }

            switch (state_) {
                case stopped:
                    state_ = receiving_request_head;
                    response_.head() = HttpResponseHead();
                    async_read(request_.head(), 
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case receiving_request_head:
                    state_ = preparing;
                    if (watch_state_ == watch_stopped 
                        && request_.head().content_length.get_value_or(0) == 0) {
                            watch_state_ = watching;
                            async_read_some(boost::asio::null_buffers(), 
                                boost::bind(&HttpProxy::handle_watch, this, _1));
                    }
                    on_receive_request_head(
                        request_.head(), 
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case preparing:
                    if (bytes_transferred.get_bool()) {
                        if (!http_to_server_)
                            http_to_server_ = new HttpSocket(get_io_service());
                        state_ = connectting;
                        http_to_server_->async_connect(request_.head().host.get(), 
                            boost::bind(&HttpProxy::handle_async, this, _1, Size()));
                    } else {
                        state_ = transferring_request_data;
                        transfer_request_data(
                            boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    }
                    break;
                case connectting:
                    state_ = sending_request_head;
                    http_to_server_->async_write(request_.head(), 
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case sending_request_head:
                    state_ = transferring_request_data;
                    transfer_request_data(
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case transferring_request_data:
                    if (is_local()) {
                        on_receive_request_data(transfer_buf_);
                        transfer_buf_.consume(transfer_buf_.size());
                    }
                    state_ = local_processing;
                    if (watch_state_ == watch_stopped) {
                        watch_state_ = watching;
                        async_read_some(boost::asio::null_buffers(), 
                            boost::bind(&HttpProxy::handle_watch, this, _1));
                    }
                    response_.head().connection = request_.head().connection;
                    local_process(
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case local_processing:
                    if (is_local()) {
                        state_ = receiving_response_head;
                        on_receive_response_head(response_.head());
                        if (!response_.head().content_length.is_initialized()) {
                            if (bytes_transferred.is_size_t())
                                response_.head().content_length.reset(bytes_transferred.get_size_t());
                            else
                                response_.head().connection.reset(http_field::Connection());
                        }
                        if (!response_.head().connection.is_initialized()) {
                            response_.head().connection.reset(http_field::Connection());
                        }
                        handle_async(ec, Size());
                    } else {
                        state_ = receiving_response_head;
                        http_to_server_->async_read(response_.head(), 
                            boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    }
                    break;
                case receiving_response_head:
                    if (!is_local()) {
                        on_receive_response_head(response_.head());
                        if (!response_.head().connection.is_initialized()) {
                            response_.head().connection.reset(http_field::Connection());
                        }
                        if (response_.head().err_msg.empty())
                            response_.head().err_msg = "OK";
                    }
                    state_ = sending_response_head;
                    async_write(response_.head(), 
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case sending_response_head:
                    state_ = transferring_response_data;
                    transfer_response_data(
                        boost::bind(&HttpProxy::handle_async, this, _1, _2));
                    break;
                case transferring_response_data:
                    on_finish();
                    if (!response_.head().connection
                        || response_.head().connection.get() == http_field::Connection::close) {
                            state_ = exiting;
                            if (watch_state_ != watching) {
                                delete this;
                            } else {
                                error_code ec;
                                shutdown(boost::asio::socket_base::shutdown_send, ec);
                                boost::asio::ip::tcp::socket::cancel(ec);
                            }
                    } else {
                        state_ = stopped;
                        if (watch_state_ != watching) {
                            // restart
                            watch_state_ = watch_stopped;
                            handle_async(ec, Size());
                        } else {
                            error_code ec;
                            boost::asio::ip::tcp::socket::cancel(ec);
                        }
                    }
                    break;
                default:
                    assert(0);
                    break;
            }
        }
Exemple #27
0
int fileclient::connect_server()
{
    int ret = -1;

	int epoll_handle = -1;
	struct epoll_event sock_event;
    struct epoll_event events[8];
    int error = 0;
    int len = 0;
    int sockfd = -1;
    int epoll_ret = -1;

	if ((epoll_handle = epoll_create(8)) == -1)
	{
        return false;
	}

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		printf("socket: %s\n", strerror(errno));
		goto EXPOUT;
	}

	len = sizeof(_serveraddr);

	sock_event.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLERR | EPOLLPRI;
	sock_event.data.fd = sockfd;

	(void)set_non_block(sockfd);

	epoll_ctl(epoll_handle, EPOLL_CTL_ADD, sockfd, &sock_event);
	if ((::connect(sockfd, (struct sockaddr*) &_serveraddr, (socklen_t)len)) < 0)
	{
		if (errno != EINPROGRESS)
		{
            printf("connect %s : %d fail, reason: %s\n", inet_ntoa(_serveraddr.sin_addr),
            		ntohs(_serveraddr.sin_port), strerror(errno));
            goto EXPOUT;
		}
	}
	else
	{
        ret = sockfd;
		goto EXPOUT;
	}

	/* 只检测这一个socket */
    epoll_ret = epoll_wait(epoll_handle, events, 8, 1000);
	if(epoll_ret == 0) /* 没有任何事件发生,返回超时错误 */
	{
        goto EXPOUT;
	}
	else if(epoll_ret < 0)
	{
		goto EXPOUT;
	}
	else /* 有事件发生,但是为了更安全起见,检测下是否是错误事件 */
	{
		error = 0;
		len = sizeof(int);
		if(0 == getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, (socklen_t*)&len))
		{
            if(error != 0)
            {
            	printf("connect  %s %d error: %s \n", inet_ntoa(_serveraddr.sin_addr),
                		ntohs(_serveraddr.sin_port),  strerror(error));
                errno = error;
                ret = SOCK_CONNECT_ERROR;
            }
            else
            {
			    ret = sockfd;
            }
		}
	}

EXPOUT:
	if (epoll_handle > 0)
	{
		close(epoll_handle);
	}
	if (ret <= 0)
	{
		if (sockfd > 0)
			close(sockfd);
	}
	else
	{
//		printf("connect %s %d success \n", inet_ntoa(_serveraddr.sin_addr),
//        		ntohs(_serveraddr.sin_port));
	}
	return ret;
}
Exemple #28
0
int main(int argc, char *argv[])
{
    int ret = 0;
    struct stat st;
    int status = 0;
    int opt;

    progname = argv[0];

    while ((opt = getopt (argc, argv, "D:b:fc:sh")) != -1)
    {
        switch (opt)
        {
            case 'D': device_path = optarg; if (strlen(device_path) == 0) syntax(); break;
            case 'b': baudrate = atoi(optarg); if (baudrate == 0) syntax(); break;
            case 'f': flowcontrol = 1; break;
            case 'c': csize = atoi(optarg); if ((csize < 5) || (csize > 8)) syntax(); break;
            case 's': twostopbits = 1; break;
            case 'h': // fall through
            default:
                syntax();
                break;
        }
    }

    if (device_path == NULL)
        syntax();

    if (stat(device_path, &st) != 0)
    {
        fprintf(stderr, "Error: %s does not exist\n", device_path);
        ret = EXIT_FAILURE;
        goto main_init_error;
    }

    serial_fd = open(device_path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY);
    if (serial_fd < 0)
    {
        fprintf(stderr, "Error: unable to open %s\n", device_path);
        ret = EXIT_FAILURE;
        goto main_init_error;
    }

    if (configure_serial_port(serial_fd) != 0)
    {
        fprintf(stderr, "Error: unable to configure %s\n", device_path);
        ret = EXIT_FAILURE;
        goto main_init_error;
    }

    // set standard file descriptors to non-blocking
    set_non_block(STDIN_FILENO, 1);
    set_non_block(STDOUT_FILENO, 1);
    set_non_block(STDERR_FILENO, 1);

    signal(SIGINT, handle_terminate_signal);
    signal(SIGTERM, handle_terminate_signal);

    forward(serial_fd);

main_init_error:
    if (serial_fd >= 0)
    {
        close(serial_fd);
        serial_fd = -1;
    }
    return ret;
}
//与服务端建立连接
int32_t CTCPSocket::Connect(const char* szRemoteIP, uint16_t nPort, bool bNonBlock/* = true*/, int32_t nTimeout/* = 0*/)
{
	if (NULL == szRemoteIP)
	{
		return E_REMOTEIP;
	}

	//判断套接字类型
	if (enmSocketType_Communicate != m_socketType)
	{
		return E_SOCKETTYPE;
	}

	//套接字是否打开
	if ((enmInvalidSocketFD == m_socketFD) || (enmSocketStatus_Opened != m_socketStatus))
	{
		return E_SOCKETNOTCREATED;
	}

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(szRemoteIP);
	addr.sin_port = htons(nPort);

	if (bNonBlock)
	{
#ifndef WIN32
		set_non_block(m_socketFD);
		//int flags = fcntl(m_socketFD, F_GETFL, 0);
		//fcntl(m_socketFD, F_SETFL, flags | O_NONBLOCK);
#else
		unsigned long ul = 1;
		int32_t ret = ioctlsocket(m_socketFD, FIONBIO, (unsigned long*)&ul);
		if (ret == SOCKET_ERROR)
		{
			return E_SOCKETCONTROL;
		}
#endif
	}

	//与服务器端建立连接
	int32_t ret = connect(m_socketFD, (const struct sockaddr*)&addr, sizeof(addr));
	if (0 != ret)
	{
#ifdef WIN32
		DWORD error = WSAGetLastError();
		if (error != WSAEINPROGRESS && error != WSAEWOULDBLOCK)
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#else
		if (errno != EINPROGRESS)
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
		else if (bNonBlock)
		{
			m_socketStatus = enmSocketStatus_Connecting;
			return E_SOCKET_CONNECTING;
		}
#endif
	}

	//非阻塞并等待超时
	if (bNonBlock && (0 < nTimeout))
	{
		timeval tv;
		tv.tv_sec = nTimeout / MS_PER_SECOND;
		tv.tv_usec = (nTimeout % MS_PER_SECOND) * US_PER_MS;

		fd_set rset;
		fd_set wset;
		FD_ZERO(&rset);
		FD_SET(m_socketFD, &rset);
		wset = rset;

		ret = select((int)m_socketFD + 1, &rset, &wset, NULL, &tv);
		if (0 >= ret)
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#ifndef WIN32
		if ((FD_ISSET(m_socketFD, &rset)) && (FD_ISSET(m_socketFD, &wset)))
		{
			CloseSocket();
			return E_SOCKETCONNECT;
		}
#endif
	}

	//更新套接字状态
	m_socketStatus = enmSocketStatus_Connected;

	return S_OK;
}
Exemple #30
0
/* *************************************************
 * output : conn_fd(存放连接成功后的fd)
 * return : success (OK) error(errcode)
 * comment: 默认的超时时间是 1s
 * ************************************************/
int non_block_conn(int *conn_fd, const char *ip, unsigned short port)
{
    int ret = OK;
	int sockfd = 0;
	struct sockaddr_in server_addr;
    socklen_t sockaddr_len = sizeof(server_addr);
	int epoll_handle = -1;
	struct epoll_event sock_event;
    struct epoll_event events[8];
    int error = 0;
    int len = 0;

	if ((epoll_handle = epoll_create(32)) == -1)
	{
		printf("epoll_create: %s\n", strerror(errno));
		return ERROR;
	}

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		printf("socket: %s\n", strerror(errno));
		goto EXPOUT;
	}

	len = sizeof(server_addr);
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family     = AF_INET;
	server_addr.sin_addr.s_addr= inet_addr(ip);
	server_addr.sin_port       = htons(port);

	sock_event.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLERR | EPOLLPRI;
	sock_event.data.fd = sockfd;

	(void)set_non_block(sockfd);

	epoll_ctl(epoll_handle, EPOLL_CTL_ADD, sockfd, &sock_event);
	if ((ret = connect(sockfd, (struct sockaddr*) &server_addr, sockaddr_len)) < 0)
	{
		if (errno != EINPROGRESS)
		{
            printf("connect %s : %d fail, reason: %s\n", ip, port, strerror(errno));
            goto EXPOUT;
		}
	}
	else
	{
		*conn_fd = sockfd;
		goto DONE;
	}

	/* 只检测这一个socket */
	ret = epoll_wait(epoll_handle, events, 8, 5*1000);
	if(ret == 0) /* 没有任何事件发生,返回超时错误 */
	{
        ret = ERROR_SOCK_CONN_TIMEOUT;
        goto EXPOUT;
	}
	else if(ret < 0)
	{
		ret = ERROR_EPOLL_WAIT;
		goto EXPOUT;
	}
	else /* 有事件发生,但是为了更安全起见,检测下是否是错误事件 */
	{
		*conn_fd = sockfd;
		error = 0;
		len = sizeof(int);
		if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, (socklen_t*)&len))
		{
			ret = ERROR;
		}
		else
		{
            if(error != 0)
            {
            	printf("error: %s \n", strerror(error));
                errno = error;
            	return ERROR;
            }
            else
            {
			    ret = OK;
            }
		}
	}


DONE:
    if (epoll_handle > 0)
	{
		close(epoll_handle);
	}
    dlog1("connect %s %d success \n", ip, port);
	return OK;
EXPOUT: *conn_fd = -1;
	if (sockfd > 0)
		close(sockfd);
	return ret;
}