epoll+lua単純ゲームサーバ(四)
1840 ワード
/** , lua */
void read_fd(int fd, lua_State *L)
{
//
if(fds[fd] < 0)
return;
char buf[READ_SIZE];
int ret, idx, done;
client_data *client;
//
idx = fds[fd];
client = clients[idx];
//
done = client->read_len;
ret = read(fd, buf, READ_SIZE);
//
if(ret == 0 || (ret < 0 && ret != EAGAIN))
remove_fd(fd, L);
else
{
//
do
{
//
done += ret;
if(done >= READ_SIZE)
{
remove_fd(fd, L);
return;
}
memcpy(client->read + client->read_len, buf, ret);
client->read_len = done;
}
while((ret = read(fd, buf, READ_SIZE)) > 0);
// , 4
if(client->data_len == 0 && client->read_len >= 4)
{
int i;
for(i = 0; i < 4; i++)
client->data_len = (client->data_len << 8) | client->read[i];
}
// TODO
if(client->data_len + 4 == client->read_len)
{
client->read[client->read_len] = '\0';
// lua
lua_State *Lx = lua_newthread(L);
lua_getglobal(Lx, F_ONREAD); //lua onread
lua_pushinteger(Lx, fd);
lua_pushstring(Lx, client->read + 4);
ret = lua_pcall(Lx, 2, LUA_MULTRET, 0);
if(ret != 0)
fprintf(stderr, "%s
", lua_tostring(Lx, -1));
lua_settop(L, 0);
//
client->data_len = client->read_len = 0;
//
client->last = now();
}
}
}