开发者

comparing strings and decoded unicode in python3

I'm doing some socket/select programming and one of my events is triggered by the incoming byte string of 'OK'. I'm using utf_8 to encode everything sent from the server and decoding it on the client. However, my client comparisons aren't working and my if statement never evaluates to true. Here is the code in question:

Server side:

def broadcast_string(self, data, omit_sock): # broadcasts data utf_8 encoded to all socks
    for sock in self.descriptors:
        if sock is not self.server and sock is not omit_sock:
            sock.send(data.encode('utf_8'))
    print(data)

def start_game(self): # i call this to send 'OK'
    data = 'OK'
    self.broadcast_string(data, 0)
    self.new_round()

Client side:

else:   # got data from server
    if data.decode('utf_8') == 'OK': # i've tried substituting this with a var, no luck
        self.playstarted = True
    else:
        sys.stdout.write(data.decode('utf_8') + "\n")
        sys.stdout.flush()

    if self.playstarted is True: # never reached because if statement never True
        command = input("-->")

I'v开发者_高级运维e read this and I think I'm following it but apparently not. I've even done the examples using the python shell and have had them evaluate to True, but not when I run this program.

Thanks!


TCP sockets don't have message boundaries. As your last comment says you are getting multiple messages in one long string. You are reponsible for queuing up data until you have a complete message, and then processing it as one complete message.

Each time select says a socket has some data to read, append the data to a read buffer, then check to see if the buffer contains a complete message. If it does, extract just the message from the front of the buffer and process it. Continue until no more complete messages are found, then call select again. Note also you should only decode a complete message, since you might receive a partial UTF-8 multi-byte character otherwise.

Rough example using \n as a message terminator (no error handling):

tmp = sock.recv(1000)
readbuf += tmp
while b'\n' in readbuf:
    msg,readbuf = readbuf.split(b'\n',1)
    process(msg.decode('utf8'))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜