epoll + lua 简单游戏服务器(五)

/**空闲处理,断开空闲的连接*/
void idle_fds(lua_State *L)
{
	client_data *client;
	int i;
	long n;
	n = now();

        //做fds和clients对应为了这里快一点(65535 vs 1000)
	for(i = 0; i < MAX_CLIENT; i++)
	{
		client  = clients[i];
                //超过一定的毫秒数即断开
		if(client != NULL && n - client->last >= IDLE)
		{
			fprintf(stdout, "close %d for idle\n", client->fd);
			remove_fd(client->fd, L);
		}
	}
}


/**绑定到lua环境的函数 _send(fd, s)
int _send(lua_State *L)
{
	const char *s = lua_tostring(L, -1);
	int fd = lua_tointeger(L, -2);

	int ret, i, len;
	len = strlen(s);
	char res[len + 4];

	//添加头
	for(i = 0; i < 4; i++)
		res[i] = (len >> (3 - i) * 8) & 0xff;
	memcpy(res + 4, s, len);
	len += 4;

        //循环发送,直至完成,TODO 判断缓冲区是否可写
	ret = send(fd, res, len, 0);
	if(ret < 0)
	{
		remove_fd(fd, L);
		return luaL_error(L, "error send");
	}
	else
	{
		len -= ret;
		while(len > 0)
		{
			ret = send(fd, res + ret, len, 0);
			len -= ret;
		}
	}
	fprintf(stdout, "SEND: %s\n", s);
	return 0;
}


/**绑定到lua的函数 _close(fd)*/
int _close(lua_State *L)
{
	int fd = lua_tointeger(L, -1);
	remove_fd(fd, L);
	return 0;
}

你可能感兴趣的:(epoll)