1

我有一個應該連續發送數據並等待客戶端提示停止,設置變量或傳輸日誌文件內容的python服務器。目前我只是試圖從客戶端恢復提示。Python asyncio資源不可用

我試圖利用ASYNCIO這樣做,但我遇到了以下錯誤:

(,BlockingIOError(11 '資源暫時不可用'))

我的服務器代碼:

loop = asyncio.get_event_loop() 

async def server(): 
     s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 

     host = '' 
     port = 1194 

     s.bind((host,port)) 
     print ("bouned to port") 
     s.listen(4) 
     while True: 

       conn, addr = await loop.sock_accept(s) 

       if conn: 
         print ("connected to address: {!r}".format(addr)) 
#      print (conn) 
         d = loop.create_task(temp_sender(conn)) 
         try: 
          await d 
         except StopIteration: 
          pass 
async def temp_sender(conn): 
     print("temp_sender activated") 

     try: 
       data = await conn.recv(1024) 
       print (data) 
       sdata = data.decode() 
       print (sdata) 
       conn.writeline("the set temp is: ", sdata) 
     except: 
       print (sys.exc_info()) 
       pass 

嘗試接收來自conn的數據時temp_sender函數中發生錯誤。

我該如何解決這個可用性錯誤?

回答

1
import asyncio 
@asyncio.coroutine 
def handle_echo(reader, writer): 
    data = yield from reader.read(1024) 
    # reader reads from client 
    #writer writes to client 

    message = data 
    addr = writer.get_extra_info('peername') 
    print("Received %r from %r" % (message, addr)) 

    print("Send: %r" % message) 
    writer.write(data) 
    yield from writer.drain() 

    print("Closing client socket") 
    writer.close() 

loop = asyncio.get_event_loop() 
##the code below will run whenever a new client connects (multiple at a time) 
coro = asyncio.start_server(handle_echo, '127.0.0.1',1194, loop=loop) 
server = loop.run_until_complete(coro) 

# Serve requests until Ctrl+C is pressed 
print('Serving on {}'.format(server.sockets[0].getsockname())) 
try: 
    loop.run_forever() 
except KeyboardInterrupt: #server stops on a keyboard interrupt 
    pass 

# Closing the server 
server.close() 
loop.run_until_complete(server.wait_closed()) 
loop.close() 
+0

請使用使用的編程語言標記問題 – kism3t

+0

這適用於python3.4.x – Aravind