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)