-1

下面是我的简单服务器代码。

我想存储/打印任何客户端发送数据的地址。

例如输出应该是:

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)

有人告诉我使用 dict 但我不知道如何使用?

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)
4

1 回答 1

-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)
于 2012-12-12T05:15:41.653 回答