以下是我的簡單服務器代碼。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)
這裏有什麼真正的問題?爲什麼你不能將IP地址存儲爲字典的關鍵字?你想說啥? –
我明白了,更新和謝謝。 – user1788175