简体   繁体   中英

Python 3 Sockets

I'm working with a small script that creates a listening socket and receives a file from a client.

This code works in python 2.7 but I cannot figure out why it doesn't work with python 3. Can someone help me make this work?

import socket

(HOST, PORT) = ('', 19129)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT));
s.listen(1);
conn, addr = s.accept()

with open('LightData.txt', 'wb') as f:
    while True:
        t = conn.recv(20)
        print (t)
        if t == "":
            s.close()
            break

        f.write(t)

It gets stuck somewhere at if t==: , because in the console it keeps printing

b''
b''
b''
b''
b''
b''
b''

In python2:

>>> b'' == ''
True

In python3:

>>> b'' == ''
False

So replace if t == "": with if t == b'':

The problem is here:

if t == "":

Your t is binary data, a bytes object. No bytes object is ever equal to a Unicode str object. So this will always fail. Try it yourself:

>>> b'' == ''
False

The reason this worked in Python 2 is that byte-strings and strings were the same type, while unicode strings were a different type. In Python 3, Unicode strings and strings are the same type, while bytes are a different type.


If you'd written this the idiomatic way in Python 2, it would continue to work in Python 3:

if not t:

In Python, you usually just check whether a value is "truthy" or "falsey". A non-empty string and a non-empty byte-string are both truthy; empty ones are both falsey. The only time you want to write a check like if t == "" is when you explicitly want to check only empty strings, and have it fail for None , or False , or empty bytestrings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM