예제 #1
0
int
main(int argc , char **argv)
{
	int fd , len;
	fd = open(argv[1], O_RDWR);
	if (fd < 0) {
		perror("open file failed :");
		return -1;
	}


	SetNonBlock(fd, true);
	
	char buf[2048];
	len = read(fd, buf, sizeof(buf) );
	if (len > 0) {
		buf[len] = '\0';
		printf("read %d bytes, and data is :%s\n",len, buf);
	} else if (len < 0)
		perror("read file failed :");

	close(fd);

	return 0;
	
}
예제 #2
0
/* create non blocking listener sprocket on port, null on failure */
struct sprock_t *ServSprockMake(unsigned short port) {
	int sock;
	struct sockaddr_in servaddr;
	struct sprock_t *sprocket;
	
	if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) return NULL;
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(port);

	if (bind(sock, (struct sockaddr *)&servaddr,
		sizeof(servaddr)) < 0) return NULL;
	if (listen(sock, BACKLOG) < 0) return NULL;
	if (SetNonBlock(sock) < 0) return NULL;   

	if ((sprocket = (struct sprock_t *)
		malloc(sizeof(struct sprock_t))) == NULL) return NULL;
	memset(sprocket, 0, sizeof(*sprocket));
	sprocket->fd = sock;
	sprocket->func = SERV;
	sprocket->state = INIT;
	sprocket->lastio = -1;

	return sprocket;
}
예제 #3
0
int IOHelper::Accept(int listen_fd, char* ipbuf, int* port) {
  sockaddr_in addr;
  socklen_t len_addr = sizeof(addr);
  int new_fd;
  while (true) {
    new_fd = accept(listen_fd, RCAST<sockaddr*>(&addr), &len_addr);
    if (-1==new_fd) {
      if (EINTR==errno) continue;
      return -1;
    }
    break;
  }

  bool ret = SetNonBlock(new_fd);
  if (!ret) return -2;

  if (NULL!=ipbuf) {
    inet_ntop(AF_INET, &addr.sin_addr, ipbuf, INET_ADDRSTRLEN);
  }

  if (NULL!=port) {
    *port = ntohs(addr.sin_port);
  }
  return new_fd;
}
예제 #4
0
int clsAsyncPipeMng::Init(clsConfigure *poConf)
{
    int iRet;
    m_tIdleIdxList.clear();

    memset(m_aiGroupCnt, 0, sizeof(m_aiGroupCnt));

    for (uint32_t i = 0; i < MAX_ASYNC_PIPE_NUM; ++i)
    {
        iRet = MakeNonBlockPipe(m_aaAsyncPipe[i][0],
                m_aaAsyncPipe[i][1]);
        AssertEqual(iRet, 0);

#if 0
        iRet = SetNonBlock(m_aaAsyncPipe[i][0], false);
        AssertEqual(iRet, 0);
#endif

        m_tIdleIdxList.push_back(i);

        m_aiEntityIDMap[i] = INVALID_ENTITY_ID;
    }

    m_poCertain = clsCertainWrapper::GetInstance();
    m_iMaxGroupLimit = m_poCertain->GetCertainUser()->GetControlGroupLimit();
    CertainLogZero("MAX_ASYNC_PIPE_NUM %u m_iMaxGroupLimit %u",
            MAX_ASYNC_PIPE_NUM, m_iMaxGroupLimit);

    return 0;
}
예제 #5
0
CLS_TCPConnect::CLS_TCPConnect(int iSocket, const char *strIP, int iPort)
    :CLS_Socket(iSocket, SS_CONNECT)
{
    strcpy(m_strIP, strIP);
    m_iPort=iPort;
    SetSocketProp();
    SetNonBlock();
}
예제 #6
0
CLS_TCPConnect::CLS_TCPConnect()
    :CLS_Socket()
{
    m_strIP[0]=0;
    m_iPort=-1;
    SetSocketProp();
    SetNonBlock();
}
예제 #7
0
void CLS_TCPConnect::SetConnectProp(int iSocket, const char *strIP, int iPort)
{
    if(m_iSocket>0)
        CloseSocket();
    m_iSocket=iSocket;
    m_iStatus=SS_CONNECT;
    strcpy(m_strIP, strIP);
    m_iPort=iPort;
    SetSocketProp();
    SetNonBlock();
}
예제 #8
0
bool NHandsFree::
InetConnect(int port)
{
	int sock;
	sockaddr_in sa;

	assert(m_hfpd_state == NHS_HFPD_DISCONNECTED);
	assert(m_sock < 0);

	sock = socket(PF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
		ndebug::out(ndebug::LOG_ERR, "NHandsFree: %s:%s(%d) - "
			    "Error creating socket(%d) - %s",
			    __FILE__, __FUNCTION__, __LINE__,
			    errno, strerror(errno));
		return false;
	}

	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

	if (!SetNonBlock(sock, true)) {
		ndebug::out(ndebug::LOG_ERR, "NHandsFree: %s:%s(%d) - "
			    "Error setting nonblock on socket(%d) - %s",
			    __FILE__, __FUNCTION__, __LINE__,
			    errno, strerror(errno));
		close(sock);
		return false;
	}

	if (connect(sock, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
		if (errno == EINPROGRESS) {
			m_sock = sock;
			m_hfpd_state = NHS_HFPD_CONNECTING;
			return true;
		}

		ndebug::out(ndebug::LOG_ERR, "NHandsFree: %s:%s(%d) - "
			    "Error connecting socket(%d) - %s",
			    __FILE__, __FUNCTION__, __LINE__,
			    errno, strerror(errno));
		close(sock);
		return false;
	}

	m_hfpd_state = NHS_HFPD_CONNECTED;
	m_sock = sock;
	Connected();
	return true;
}
예제 #9
0
bool NHandsFree::
UnixConnect(const char *sockname)
{
	int sock;
	sockaddr_un sa;

	assert(m_hfpd_state == NHS_HFPD_DISCONNECTED);
	assert(m_sock < 0);

	sock = socket(PF_UNIX, SOCK_STREAM, 0);
	if (sock < 0) {
		ndebug::out(ndebug::LOG_ERR, "NHandsFree: %s:%s(%d) - "
			    "Error creating socket(%d) - %s",
			    __FILE__, __FUNCTION__, __LINE__,
			    errno, strerror(errno));
		return false;
	}

	sa.sun_family = AF_UNIX;
	strncpy(sa.sun_path, sockname, sizeof(sa.sun_path));

	if (!SetNonBlock(sock, true)) {
		ndebug::out(ndebug::LOG_ERR, "NHandsFree: %s:%s(%d) - "
			    "Error setting nonblock on socket(%d) - %s",
			    __FILE__, __FUNCTION__, __LINE__,
			    errno, strerror(errno));
		close(sock);
		return false;
	}

	if (connect(sock, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
		if (errno == EINPROGRESS) {
			m_sock = sock;
			m_hfpd_state = NHS_HFPD_CONNECTING;
			return true;
		}

		ndebug::out(ndebug::LOG_ERR, "NHandsFree: %s:%s(%d) - "
			    "Error connecting socket(%d) - %s",
			    __FILE__, __FUNCTION__, __LINE__,
			    errno, strerror(errno));
		close(sock);
		return false;
	}

	m_hfpd_state = NHS_HFPD_CONNECTED;
	m_sock = sock;
	Connected();
	return true;
}
예제 #10
0
inline SOCKET mksock()
{
	/*Initialize RAW socket UDP level*/
	SOCKET sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);

	/*setup some more settings for polling*/
	if(!IS_VALID_SOCK(sock))
		error(1, 0, "Error socket initialization");
	if(SetNonBlock(sock) < 0)
		error(1, errno, "Error switching socket to non-block mode.");
	if(SetReusable(sock) < 0)
		error(1, errno, "Error making socket reusable");

	return sock;
}
예제 #11
0
void EpollListenStrategy::PostInput() {
    if (!m_canInput) {
        return;
    }

    Host peerHost;
    auto sockAddr = peerHost.SockAddr();
    auto sockAddrLen = peerHost.SockAddrLen();
    const auto& listenSockId = m_listenSocket.GetSockId();
    while (true) {
        auto sockId = accept(listenSockId, sockAddr, &sockAddrLen);
        if (sockId == INVALID_SOCKID) {
            const auto error = SAGetLastError();
            if (IsInterrupted(error)) {
                continue;
            }

            if (IsWouldBlock(error)) {
                m_canInput = false;
                break;
            }

            switch(error) {
            case EMFILE:
            case ENFILE:
            case ENOBUFS:
            case ENOMEM:
            case EPERM:
                MZ_ASSERT_TRUE(false);
                break;
            default: break;
            };

            NS_SHARE::Log(MZ_LOG_DEBUG, "Socket Error: socket close, error[%d]. [%s:%d]\n", error, __FILE__, __LINE__);
            m_listenSocket.Close();
            m_listenSocket.OnError(error);
            break;
        }

        SetNonBlock(sockId);

        if (!m_listenSocket.OnAccepted(sockId, peerHost)) {
            DestroySockId(sockId);
        }
    }
}
예제 #12
0
/* non blocking return accepted client given serversprock, NULL on failure */
struct sprock_t *ClntSprockAccept(struct sprock_t *parentsprock) {
	int clntsock;
	struct sockaddr_in clntaddr;
	size_t clntlen;
	struct sprock_t *sprocket;
	
	clntlen = sizeof(clntaddr);
	if ((clntsock = accept(parentsprock->fd,
		(struct sockaddr *)&clntaddr, &clntlen)) < 0) return NULL;
	if (SetNonBlock(clntsock) < 0) return NULL;

	if ((sprocket = (struct sprock_t *)
		malloc(sizeof(struct sprock_t))) == NULL) return NULL;
	memset(sprocket, 0, sizeof(struct sprock_t));
	sprocket->ipaddr = inet_ntoa(clntaddr.sin_addr);
	sprocket->fd = clntsock;
	sprocket->func = CLNT;
	sprocket->state = INIT;
	sprocket->lastio = time(NULL);
	parentsprock->child = sprocket;
	sprocket->parent = parentsprock;

	return sprocket;
}
예제 #13
0
int main()
{
    struct epoll_event ev, events[MAX_EVENTS];
    struct sockaddr_in client;
    struct sockaddr_in server;
//    const char* localhost = "127.0.0.1";
    const char* localhost = "0.0.0.0";
    int tcpfd, udpfd, nfds, confd;
    int servPort = 8888;
    socklen_t addrLen = sizeof(struct sockaddr);
    char line[MAX_LINE];
    ssize_t n;
    MYSQL connection;
    pthread_t thread;
    pthread_attr_t attr;

    //create socket
    tcpfd = CreateSocket(TCP);
    //translate ip & port into sockaddr_in format
    Ip2SocketAddr(&server, localhost, servPort);
    //bind ip & port to socket
    BindSocketAddr(&server, tcpfd);
    //begin to listen
    listen(tcpfd, LISTEN_NUM);
    //create epoll
    epfd = CreateEpoll(MAX_EVENTS);
    //set fd nonblocking mode
    SetNonBlock(tcpfd);
    //register fd event to epoll
    EpollAdd(epfd, tcpfd, EPOLLIN|EPOLLET);
    //create thread pool
    InitPool(MAX_POOL_SIZE);
    //init a connection to MySql
    conn = mysql_init(NULL);
    if(mysql_real_connect(conn, "localhost", "root", "", "test_server", 0, NULL, 0) == NULL){
	perror("no database connection...\n");
	exit(1);
    }

    while(1){
	if((nfds = EpollWait(epfd, events, 20, 500)) == -1){
	    perror("epoll_wait\n");
	    exit(-1);
	}

	for(int i = 0; i < nfds; i++)
	{
	    if(events[i].data.fd == tcpfd)
	    {
		confd = accept(tcpfd, (struct sockaddr *)&client, &addrLen);
		if(confd < 0)
		{
		    perror("accept error \n");
		    exit(1);
		}
		else
		    printf("connect %s:%d socket :%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port), confd);
//		SetNonBlock(confd);
		EpollAdd(epfd, confd, EPOLLIN|EPOLLET);

		if(IsRecvIn(&events[i]))
		    AddTask2Pool(MessageHandlerThread, (void *)&confd);
	    }
	}//for(0 to nfds)
    }
}