python中的非阻塞套接字编程

时间:2016-04-13 17:11:31

标签: python sockets nonblocking

我正在尝试编写一个非阻塞套接字代码。到目前为止,我已经尝试过这个:

server.py

import socket   

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.bind(('localhost',60003))
s.listen(1)
#print 'Connected by', addr
while 1:
    conn, addr = s.accept()
    conn.setblocking(0)
    data = conn.recv(1024)
    conn.sendall(data)
print 'the normal execution of data should continue'
print 'but when client connects, it has to echo back to the client then again continue its execution'

client.py

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost',60003))
s.sendall('Hello, world')
data = s.recv(1024)
#s.close()
print 'Received', repr(data)

我也收到此错误:socket.error: [Errno 11] Resource temporarily unavailable

无论是多少次,也不是多次更改端口号。

谢谢!

1 个答案:

答案 0 :(得分:1)

您已将服务器设置为非阻止,因此accept会立即返回错误。将服务器设置为阻止或使用select等待多个套接字上的事件。