0

simple client-server socket studying code,the server-end is:

import socket,select,time

s = socket.socket()

host = socket.gethostname()
port = 1234
s.bind((host,port))
s.listen(50)
s.setblocking(0)              # (1)

fdmap = {s.fileno():s}

p = select.epoll()
p.register(s)
while True:
    events = p.poll()
    for fd,event in events:
       if fd is s.fileno():
           c,addr = s.accept()
           c.setblocking(0)                    #(2)
           print('Got connection from: ',addr)
           p.register(c)
           fdmap[c.fileno()] = c 
       elif event & select.EPOLLIN:
           data = fdmap[fd].recv(1024)
           if not data:
               print('disconnected')
               p.unregister(fd)
               del fdmap[fd]
           else:
               print(data)

and the client-end is

import socket,time

s = socket.socket()

host = socket.gethostname()
port = 1234

s.connect((host,port))
print(s.send(b'hello server'))

My questions are:
1.AFAIK in the IO-multiplexing model,epoll.poll would block until one socket become available,so when operates on it,it shouldn't be block(should return directly),then why we should call setblocking(0) in (1),(2),what's the purpose? I tried put them off,it still works

2.when running,the client-end can be slow,it outputs 12(which is the bytes it send to server) after about 1s,I profiling it by use time.time() one by one statement,then found that the s.connect((host,port)) usually take about 1s,where am i wrong?(This happens on poll/epoll,when use select,the client-end goes very fast)

Eduardo Ramos
  • 345
  • 1
  • 10
Nowhy
  • 2,894
  • 1
  • 16
  • 13

1 Answers1

1

If you check the documentation you will see that the epoll poll function takes a timeout parameter, which defaults to -1 which means wait indefinitely. If you set the timeout to zero it will return immediately.

As for the delay in connect it's probably because connect has to do a DNS lookup of the hostname to find the IP address.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Would DNS lookups explain the delay for `select.epoll` but not for `select.select`? – Mu Mind Oct 05 '12 at 05:53
  • @MuMind Neither `select.epoll` nor `select.select` (or `select.poll`) does any DNS lookups. And what `select.epoll` delay are you talking about? – Some programmer dude Oct 05 '12 at 05:57
  • In the question they said `s.connect((host,port))` only has a delay for `poll`/`epoll`, but it goes very fast for `select`. I would think that would pretty much rule out DNS lookups as the culprit. – Mu Mind Oct 05 '12 at 06:00
  • @MuMind Yes,when i set timeout to 0,it goes fast,but I still don't get it,because as long as i set timeout large than 0,whatever,like 5,500,500000,it would block for 1 second,the "s" always be available after 1 second..? – Nowhy Oct 05 '12 at 07:36