如何找出哪个套接字客户端发送消息?

时间:2012-11-29 22:13:38

标签: python sockets

我正在开展聊天程序。我有一个服务器和客户端,多个用户可以连接到服务器。目前,我只是让服务器发回客户端发送给服务器的任何消息。我想添加一个身份验证,以便在身份验证失败时接受/拒绝连接。

客户端:

class Network:
    # initialize the socket
    def __init__(self, client, host=host, port=port):
        self.client = client;
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        self.port = port;
        self.host = host;
        self.addr = (host, port);

    # conenct to the server
    def connect(self):
        self.socket.connect(self.addr);

    # receive data from server if there is any
    def read(self):
        while True:
            time.sleep(0.1)
            try:
                data = self.socket.recv(1024);
            except:
                break;
                # instead of breaking, create "connection lost" then open the login form again
            print "in client: ", data;
            data_split = data.split("\r\n");
            for ds in data_split:
                self.client.msgbox.addMsg(ds);

    # send chat message to the server
    def send(self, msg):
        self.socket.send(msg);

    # authenticate user
    # if
    def authenticate(self, info):
        self.socket.send(info);

服务器:

class Server:
    # init the socket
    def __init__(self, host=host, port=port):
        self.host = host;
        self.port = port;
        self.addr = (host, port);
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);

    # send data to client
    def send(self, soc, data):
        try:
            soc.send(data);
        except:
            return "couldn't send message";

    # receive data from client
    def receive(self, soc):
        while True:
            try:
                return soc.recv(size);
            except:
                return disconnect;

    # connect client
    def connect(self):
        self.socket.bind(self.addr);
        self.socket.listen(5);
        self.socket_s = [self.socket];
        self.read_socs = [self.socket];
        self.write_socs = [];
        self.user_addr = {};

    # validate the user
    def validate(self, username, password):
        if username in users:
            sha = s256.new();
            sha.update(password);
            password = sha.hexdigest();

            if password == users[username]:
                print "in server: true";
                return True;
            else:
                print "in server: false";
                return False;

    # server
    def serve(self):
        while True:
            r_socs, w_socs, exceptions = select.select(self.read_socs, [], []);
            for s in r_socs:
                if s in self.socket_s:
                    print "accepting socket connect";
                    soc, address = s.accept();
                    print "in server: ", soc, address;
                    self.read_socs.append(soc);
                    self.write_socs.append(soc);
                    for ws in self.write_socs:
                        self.send(ws, "len(users) == " + str(len(self.write_socs)) + "\n");
                        print connection;
                else:
                    data = self.receive(s);
                    print "in server: " + data;
                    if auth in data:
                        ds = data.split(" ");
                        res = self.validate(ds[1], ds[2]);
                    elif data == disconnect:
                        s.close();
                        self.read_socs.remove(s);
                        self.write_socs.remove(s);
                        for ws in self.write_socs:
                            print "in server: " + ws
                            self.send(ws, "len(users) == " + str(len(self.write_socs)) + "\n");
                    else:
                        for ws in self.write_socs:
                            print "in server: " + ws;
                            self.send(ws, data);

1 个答案:

答案 0 :(得分:2)

您的设计实际上无法正常工作,因为收到的TCP消息中的数据不一定与来自另一方的单个发送相关 - 它可能是半个消息,或者是3个消息,或者是5-1 / 2条消息。如果您只是在localhost上测试,使用小消息,它通常似乎在您的测试中工作,然后当您将它放在互联网上时完全失败。这就是为什么你需要在TCP之上构建某种协议,它使用分隔符(如换行符),长度前缀(如netstrings)或自定界对象(如JSON)。

无论如何,您知道每条消息都会出现的套接字。您可以将套接字映射到用户,或者只使用套接字本身或其fds来做出决策。因此,就像您跟踪要传递给select的所有已知套接字一样,您还可以跟踪已知要进行身份验证的所有套接字。如果一个消息进入的套接字在该列表中,则它被认证;否则,该消息将被拒绝,除非它是一个身份验证消息。

假设你有一个简单的线路协议:

def __init__(self):
    self.sockets = [] # add clients here, along with listener
    self.authsockets = [] # add authenticated clients here
    self.buffers = defaultdict(str)

def loop(self):
    r, w, x = select.select([sockets], [sockets], [sockets])
    for sock in r:
        buffers[sock] = buffers[sock] + sock.recv(4096)
        lines = buffers[sock].split('\n')
        if buffers[sock][-1] != '\n':
            buffers[sock], lines = lines[-1], lines[:-1]
        else:
            buffers[sock] = ''
        for line in lines:
            processCommand(sock, line)
    # etc.

def processCommand(self, sock, command):
    if self.isAuthCommand(command):
        if self.isValidAuthCommand(command):
            self.authsockets.append(sock)
        return
    if not sock in self.authsockets:
        return # ignore commands before auth
    self.doNormalThing(command)

我已经删除了所有不相关的东西 - 处理接受,断开连接,错误,写入等等。但是你的阅读中遇到了类似的问题。首先,你假设套接字总是可写的,这是不正确的。您需要为每个套接字排队一个写缓冲区,并在select告诉您没有时写入。同样,这似乎可以在localhost上运行,但它会在互联网上崩溃。其次,写入套接字可能不会发送整个缓冲区,因此您需要查看已写入的字节数,并将缓冲区[bytecount:]保留到下一次。