Example #1
0
static int lua_connect_to(lua_State* state)
{
	int workerIdx = 0;
	while(state != g_workers[workerIdx].state)
	{
		workerIdx++;
	}

	const char *ip = lua_tostring(state, 1);
	unsigned short port = lua_tointeger(state, 2);
	
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    
    //sockfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;

    struct hostent *host;
	if(host = gethostbyname(ip))
	{
        memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);
	}
    else
	{
		addr.sin_addr.s_addr = inet_addr(ip);
	}

    //addr.sin_addr.s_addr = inet_addr(host);
    addr.sin_port = htons(port);

	
    Sock *sock = create_sock(sockfd, g_epollfds[workerIdx], workerIdx);
    g_sock_fd_map[sockfd] = sock;
    
    int flags = fcntl(sockfd, F_GETFL, 0);
	fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

    if(connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == 0)
    {
    }
    else
    {
    }
    
    heart_beat_sock(sock, time(0));

    lua_pushinteger(state, sockfd);
    //printf("workerIdx: %d \n", workerIdx);
    add_connector_to_worker(&g_workers[workerIdx], sock);
    
    //lua_pop(state, 1);

    return 1;
}
Example #2
0
inline Sock *create_sock(int fd, int epoll_fd)
{
	Sock *sock = (Sock*)Malloc(sizeof(Sock));
	memset(sock, 0, sizeof(Sock));
	sock->fd = fd;
	sock->legal = true;

	sock->epoll_fd = epoll_fd;

	heart_beat_sock(sock);

	sock_num++;

	return sock;
}