2015-04-23 42 views
0

我想問如何跳過接收函數。檢查是否收到消息或跳過它(python 3.4)

def client(): 
    try: 
     b = bytes.decode(h.recv(1024)) 
     print("The recieved message : ",b) 
     b1 = str.encode(b) 
     c.sendall(b1) 
     h.sendall(b1) 
     y.sendall(b1) 
    except Exception: 
     pass 
    try: 
     g = bytes.decode(y.recv(1024)) 
     print("The recieved message : ",g) 
     g1 = str.encode(g) 
     c.sendall(g1) 
     h.sendall(g1) 
     y.sendall(g1) 
    except Exception: 
     pass 

所以我需要做的是檢查是否有來自客戶端的消息:

  • 如果是的話,打印和發送。
  • 如果否,跳過該功能去與其他客戶端進行覈對。

回答

0

您需要輪詢機制。最簡單的是select

import select 

def client(): 
    sockets, _, _ = select.select([h, y], [], []) 
    # If h or y has data, select exits and returns these sockets 

    for sock in sockets: 
     try: 
      data = sock.recv(1024) 
      if data == '': 
       # sock was disconnected handle that 
       continue 

      # Process data here 
     except Exception: 
      continue 
+0

仍然沒有收到來自客戶端的消息。 – MKM

+0

@ user4823915:您發佈的代碼(http://pastebin.com/PugZRPXn):您應該在while循環中調用'select.select'。你也叫'sendall(g1)',但'g1'不再被定義,而是用數據來代替:'c.sendall(data)' – myaut

+0

我試過了,它不工作,我認爲它沒有得到該消息,因爲它不能打印它。 – MKM

相關問題