所以我对Python套接字模块有一个问题,这完全困扰了我。我在互联网上搜索了答案,但似乎没有什么能适用于我的情况。问题是这个。我尝试使用套接字将数据从我的主计算机上的一个覆盆子pi或单独的进程发送到我的主计算机。当我尝试这样做时,我得到标题中看到的错误。但是,我也有一个网站可以通过ajax调用使用完全相同的代码,它工作正常!我真的找不到代码之间的任何区别,当我从我的Pi或Python shell执行完全相同的代码时,它只是简单地工作。
服务器代码:
self.ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Bind socket to local host and port
#pdb.set_trace()
try:
self.ServerSocket.bind((HOST, self.portnum)) # HOST is "", portnum is 8001
except socket.error as msg:
print ("Bind failed. Error Code : ", str(msg))
sys.exit()
#Start listening on socket
while (self.bServerShutdown==False):
# wait to get packet
while True:
# addr is a tupl, so ip = addr[0] port = addr[1]
# Shortened method: data, (ip, port) = self.ServerSocket.recvfrom(1024)
data, addr = self.ServerSocket.recvfrom(1024) # buffer size is 1024 bytes
ip=addr[0]
port=addr[1]
Ajax代码(在从网站调用时起作用):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = (ipAddress, 8001) # ipAddress = '127.0.0.1' Since site is running on localhost
try:
sent = sock.sendto(Command.encode('utf-8'), server_address)
sock.setblocking(0)
ready = select.select([sock], [], [], 5)
if ready[0]:
data = sock.recv(4096)
#logging.info("received '%s'".format(data))
else:
#logging.info("Timeout")
data=b'Service Manager Timeout. Is it running?\r\n'
except:
continue
' 代码I在shell中使用(不起作用):
import socket
import select
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('127.0.0.1', 8001)
sent = sock.sendto('test command'.encode('utf-8'), server_address)
sock.setblocking(0)
ready = select.select([sock], [], [], 5)
if ready[0]:
data = sock.recv(4096)
else:
data ='timeout'
所以回顾一下,我的服务器代码正在运行。当我导航到localhost,它被设置为监视我的计算机数据时,一切都很好。它使得第二个代码片段中的ajax调用和数据返回正常。当我从Python shell尝试第三个代码片段时,它返回错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BlockingIOError: [Errno 11] Resource temporarily unavailable
那到底是怎么回事?我错过了一些非常简单的东西,还是更复杂的东西?任何帮助将不胜感激。