如何使用socket.select? [英] How do i use socket.select?

查看:104
本文介绍了如何使用socket.select?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用套接字选择"功能的帮助.

I need some help using socket "select" function.

我的服务器代码如下:

while true do
    for _,server in pairs(servers) do
        local client = server:accept()

        client:settimeout(5)

        local line, err = client:receive()
        if not err then
            client:send(line .. "_SERVER_SIDE\n")
        else
            client:Send("___ERRORPC"..err)
        end

        client:close()
    end
end

但是现在我要使用选择功能,而不是像这样进行永久循环.

But now i want to use the select function instead of make a forever loop like this.

阅读此内容: http://w3.impa.br/~diego /software/luasocket/socket.html

我知道我可以使用比以下类似的东西

I know that i can use something simmilar than:

socket.select(servers, nil, 5)

但是我不知道如何在上面的代码中使用它.谁能帮我吗?

But i don´t know how i can use this on the code above. Can anyone help me?

我将不得不在一会儿true语句中使用它吗?

I will have to use this inside a while true statement?

读取操作(第一个参数)意味着我只能进行接受/接收]?秒参数意味着我只能发送?

The reading operation (first parameter) means that i can only make an accept/receive]? And the seconds parameter means that i can only make a send?

推荐答案

select的文档中:在接受接受的调用之前,在具有接收套接字参数的服务器套接字中调用select并不能保证接受会立即返回. settimeout方法或accept可能会永远阻塞."这意味着您需要在accept调用之前使用settimeout,但是假设您拥有可以在servers表中使用的打开的连接列表,则可以通过以下方式使用select:

From the documentation for select: "calling select with a server socket in the receive parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever." This means that you'd need to use settimeout before your accept call, but assuming you have a list of opened connections you can work with in servers table, you can use select in the following way:

local canread = socket.select(servers, nil, 1)
for _,client in ipairs(canread) do
  local line, err = client:receive()
  if not err then
      client:send(line .. "_SERVER_SIDE\n")
  else
      client:send("___ERRORPC"..err)
  end
end

socket.select将最多阻塞1秒钟,但是如果您提供的列表中有一个可以读取的插槽,它将更快返回.如果使用socket.select(servers, nil, 0),则可以无限期阻止;如果您需要在等待输入时做一些其他工作,则短时间阻塞很有用.

socket.select will block for up to 1 second, but will return sooner if there is a socket from the list you provided that can be read from. You can block indefinitely if you use socket.select(servers, nil, 0); blocking for some short time is useful if you need to do some other work while waiting for the input.

已更新为使用ipairs而不是pairs,因为返回表同时在数字和套接字本身上进行键控,因此,如果可以读取一个套接字,则返回的数组看起来像{[1] = sock, [sock] = 1}.

Updated to use ipairs instead of pairs as the returns table is keyed both on numbers as well as on sockets themselves, so if one socket can be read from, the returned array looks like {[1] = sock, [sock] = 1}.

这篇关于如何使用socket.select?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆