2012-12-12 62 views
-1

以下是我的簡單服務器代碼。Python商店客戶端地址?

我想存儲/打印任何客戶端發送數據的地址。

例如,輸出應爲:

Connection from ('127.0.0.1', 61334) 

foo from ('127.0.0.1', 61334) 

Connection from ('127.0.0.1', 61335) 

bar from ('127.0.0.1', 61335) 

baz from ('127.0.0.1', 61334) 

qux from ('127.0.0.1', 61335) 

有人告訴我使用字典,但我不知道怎麼樣?

import select 
import socket 

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
server_socket.bind(('', 8888)) 
server_socket.listen(5) 
print "Listening on port 8888" 

read_list = [server_socket] 
while True: 
    readable, writable, errored = select.select(read_list, [], []) 
    for s in readable: 
     if s is server_socket: 
      client_socket, address = server_socket.accept() 
      read_list.append(client_socket) 
      print "Connection from", address 
     else: 
      data = s.recv(1024) 
      if data: 
       s.send(data) 
      else: 
       s.close() 
       read_list.remove(s) 
+0

這裏有什麼真正的問題?爲什麼你不能將IP地址存儲爲字典的關鍵字?你想說啥? –

+0

我明白了,更新和謝謝。 – user1788175

回答

-1

對不起,打擾傢伙。

這裏的解決方案:

import select 
import socket 

#Global Variables 
clientInfo={} 

def storeClient(client_socket,address): 
    clientInfo[client_socket]=address 


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
server_socket.bind(('', 8888)) 
server_socket.listen(5) 
print "Listening on port 8888" 

read_list = [server_socket] 
while True: 
    readable, writable, errored = select.select(read_list, [], []) 
    for s in readable: 
     if s is server_socket: 
      client_socket, address = server_socket.accept() 
      read_list.append(client_socket) 
      print "Connection from", address 
      storeClient(client_socket,address) 
     else: 
      data = s.recv(1024) 
      if data: 
       print data, "from: ", clientInfo[s] 
       s.send(data) 
      else: 
       s.close() 
       read_list.remove(s) 
+1

爲什麼你需要一個專門的方法在這裏? –

+0

因爲,我將在這個新方法下做更多的工作,並且可能會將其重命名爲storeClientInfo(適當地) – user1788175